import * as serviceDocumentService from '../services/service-document.service.js';

export const getDocumentsByFolderId = async (req, res, next) => {
  try {
    const { folderId } = req.params;
    const documents = await serviceDocumentService.getDocumentsByFolderId(folderId);
    res.json({ data: documents });
  } catch (error) {
    next(error);
  }
};

export const uploadDocument = async (req, res, next) => {
  try {
    const { folderId } = req.params;
    const userId = req.user.id;
    const file = req.file;
    const { description } = req.body;

    const document = await serviceDocumentService.uploadDocument({
      folderId,
      userId,
      file,
      description,
    });

    res.status(201).json({ data: document });
  } catch (error) {
    next(error);
  }
};

export const downloadDocument = async (req, res, next) => {
  try {
    const { folderId, documentId } = req.params;
    const { filePath, fileName, fileType } = await serviceDocumentService.getDocumentForDownload(folderId, documentId);

    res.setHeader('Content-Type', fileType);
    res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(fileName)}"`);
    res.sendFile(filePath);
  } catch (error) {
    next(error);
  }
};

export const deleteDocument = async (req, res, next) => {
  try {
    const { folderId, documentId } = req.params;
    const result = await serviceDocumentService.deleteDocument(folderId, documentId);
    res.json({ data: result });
  } catch (error) {
    next(error);
  }
};
