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

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

    const documents = await companyDocumentService.getDocumentsByCompanyId(companyId);

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

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

    const document = await companyDocumentService.uploadDocument({
      companyId,
      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/companies/:companyId/documents/:docId/download
 */
export const downloadDocument = async (req, res, next) => {
  try {
    const { companyId, docId } = req.params;

    const { filePath, fileName, fileType } = await companyDocumentService.getDocumentForDownload(
      companyId,
      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/companies/:companyId/documents/:docId
 */
export const deleteDocument = async (req, res, next) => {
  try {
    const { companyId, docId } = req.params;

    const result = await companyDocumentService.deleteDocument(companyId, docId);

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