import multer from 'multer';
import fs from 'fs';
import path from 'path';
import clubDocumentService from '../services/clubDocumentService.js';

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    fs.mkdirSync('uploads/temp', { recursive: true });
    cb(null, 'uploads/temp/');
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    cb(null, `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`);
  },
});

const upload = multer({
  storage,
  limits: {
    fileSize: 20 * 1024 * 1024,
  },
  fileFilter: (req, file, cb) => {
    const allowedExtensions = ['.pdf', '.doc', '.docx', '.txt', '.csv', '.odt', '.xlsx'];
    const allowedMimePatterns = ['pdf', 'msword', 'wordprocessingml.document', 'text/plain', 'csv', 'excel', 'opendocument.text'];
    const extensionValid = allowedExtensions.includes(path.extname(file.originalname).toLowerCase());
    const mimetypeValid = allowedMimePatterns.some((pattern) => file.mimetype && file.mimetype.toLowerCase().includes(pattern));
    if (extensionValid && mimetypeValid) {
      return cb(null, true);
    }
    cb(new Error('Nur PDF, DOC, DOCX, TXT, CSV, ODT und XLSX Dateien sind erlaubt!'));
  },
});

export const uploadMiddleware = upload.single('document');

function cleanupTempFile(file) {
  if (file?.path && fs.existsSync(file.path)) {
    fs.unlinkSync(file.path);
  }
}

export const listClubDocuments = async (req, res) => {
  try {
    const documents = await clubDocumentService.listClubDocuments(Number(req.params.clubId), req.query || {});
    res.status(200).json({ documents });
  } catch (error) {
    res.status(error.status || 500).json({ error: error.message || 'internalerror' });
  }
};

export const createClubDocument = async (req, res) => {
  try {
    const document = await clubDocumentService.createClubDocument(Number(req.params.clubId), req.user?.id || null, req.body || {}, req.file || null);
    res.status(201).json({ document });
  } catch (error) {
    cleanupTempFile(req.file);
    res.status(error.status || 500).json({ error: error.message || 'internalerror' });
  }
};

export const updateClubDocument = async (req, res) => {
  try {
    const document = await clubDocumentService.updateClubDocument(Number(req.params.clubId), Number(req.params.documentId), req.user?.id || null, req.body || {}, req.file || null);
    res.status(200).json({ document });
  } catch (error) {
    cleanupTempFile(req.file);
    res.status(error.status || 500).json({ error: error.message || 'internalerror' });
  }
};

export const archiveClubDocument = async (req, res) => {
  try {
    const document = await clubDocumentService.archiveClubDocument(Number(req.params.clubId), Number(req.params.documentId));
    res.status(200).json({ document });
  } catch (error) {
    res.status(error.status || 500).json({ error: error.message || 'internalerror' });
  }
};

export const deleteClubDocument = async (req, res) => {
  try {
    await clubDocumentService.deleteClubDocument(Number(req.params.clubId), Number(req.params.documentId));
    res.status(204).end();
  } catch (error) {
    res.status(error.status || 500).json({ error: error.message || 'internalerror' });
  }
};

export const downloadClubDocument = async (req, res) => {
  try {
    const versionNo = req.query.versionNo ? Number(req.query.versionNo) : null;
    const { document, version } = await clubDocumentService.getDocumentDownload(Number(req.params.clubId), Number(req.params.documentId), versionNo);
    if (!fs.existsSync(version.storagePath)) {
      return res.status(404).json({ error: 'filenotfound' });
    }
    res.setHeader('Content-Disposition', `inline; filename="${document.title || version.fileName}"`);
    res.setHeader('Content-Type', version.mimeType || 'application/octet-stream');
    res.sendFile(version.storagePath);
  } catch (error) {
    res.status(error.status || 500).json({ error: error.message || 'internalerror' });
  }
};

export default {
  listClubDocuments,
  createClubDocument,
  updateClubDocument,
  archiveClubDocument,
  deleteClubDocument,
  downloadClubDocument,
};
