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

/**
 * Get all documents for a project
 * GET /api/projects/:projectId/documents
 */
export const getDocuments = async (req, res, next) => {
  try {
    const { projectId } = req.params;

    const documents = await projectDocumentService.getDocumentsByProjectId(projectId);

    res.status(200).json({
      success: true,
      count: documents.length,
      data: documents,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Upload a document for a project
 * POST /api/projects/:projectId/documents
 */
export const uploadDocument = async (req, res, next) => {
  try {
    const { projectId } = req.params;
    const userId = req.userId;
    const { description } = req.body;

    const document = await projectDocumentService.uploadDocument({
      projectId,
      userId,
      file: req.file,
      description,
    });

    res.status(201).json({
      success: true,
      data: document,
      message: 'Dokument bol nahraný',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Download a document
 * GET /api/projects/:projectId/documents/:docId/download
 */
export const downloadDocument = async (req, res, next) => {
  try {
    const { projectId, docId } = req.params;

    const { filePath, fileName, fileType } = await projectDocumentService.getDocumentForDownload(
      projectId,
      docId
    );

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

/**
 * Delete a document
 * DELETE /api/projects/:projectId/documents/:docId
 */
export const deleteDocument = async (req, res, next) => {
  try {
    const { projectId, docId } = req.params;

    const result = await projectDocumentService.deleteDocument(projectId, docId);

    res.status(200).json({
      success: true,
      message: result.message,
    });
  } catch (error) {
    next(error);
  }
};
