import * as aiKurzyService from '../services/ai-kurzy.service.js';

// ==================== KURZY ====================

export const getAllKurzy = async (req, res, next) => {
  try {
    const kurzy = await aiKurzyService.getAllKurzy();
    res.json({ data: kurzy });
  } catch (error) {
    next(error);
  }
};

export const getKurzById = async (req, res, next) => {
  try {
    const { kurzId } = req.params;
    const kurz = await aiKurzyService.getKurzById(parseInt(kurzId));
    res.json({ data: kurz });
  } catch (error) {
    next(error);
  }
};

export const createKurz = async (req, res, next) => {
  try {
    const kurz = await aiKurzyService.createKurz(req.body);
    res.status(201).json({ data: kurz });
  } catch (error) {
    next(error);
  }
};

export const updateKurz = async (req, res, next) => {
  try {
    const { kurzId } = req.params;
    const kurz = await aiKurzyService.updateKurz(parseInt(kurzId), req.body);
    res.json({ data: kurz });
  } catch (error) {
    next(error);
  }
};

export const deleteKurz = async (req, res, next) => {
  try {
    const { kurzId } = req.params;
    const result = await aiKurzyService.deleteKurz(parseInt(kurzId));
    res.json({ data: result });
  } catch (error) {
    next(error);
  }
};

// ==================== UCASTNICI ====================

export const getAllUcastnici = async (req, res, next) => {
  try {
    const ucastnici = await aiKurzyService.getAllUcastnici();
    res.json({ data: ucastnici });
  } catch (error) {
    next(error);
  }
};

export const getUcastnikById = async (req, res, next) => {
  try {
    const { ucastnikId } = req.params;
    const ucastnik = await aiKurzyService.getUcastnikById(parseInt(ucastnikId));
    res.json({ data: ucastnik });
  } catch (error) {
    next(error);
  }
};

export const createUcastnik = async (req, res, next) => {
  try {
    const ucastnik = await aiKurzyService.createUcastnik(req.body);
    res.status(201).json({ data: ucastnik });
  } catch (error) {
    next(error);
  }
};

export const updateUcastnik = async (req, res, next) => {
  try {
    const { ucastnikId } = req.params;
    const ucastnik = await aiKurzyService.updateUcastnik(parseInt(ucastnikId), req.body);
    res.json({ data: ucastnik });
  } catch (error) {
    next(error);
  }
};

export const deleteUcastnik = async (req, res, next) => {
  try {
    const { ucastnikId } = req.params;
    const result = await aiKurzyService.deleteUcastnik(parseInt(ucastnikId));
    res.json({ data: result });
  } catch (error) {
    next(error);
  }
};

// ==================== REGISTRACIE ====================

export const getAllRegistracie = async (req, res, next) => {
  try {
    const { kurzId } = req.query;
    const registracie = await aiKurzyService.getAllRegistracie(kurzId ? parseInt(kurzId) : null);
    res.json({ data: registracie });
  } catch (error) {
    next(error);
  }
};

export const getRegistraciaById = async (req, res, next) => {
  try {
    const { registraciaId } = req.params;
    const registracia = await aiKurzyService.getRegistraciaById(parseInt(registraciaId));
    res.json({ data: registracia });
  } catch (error) {
    next(error);
  }
};

export const createRegistracia = async (req, res, next) => {
  try {
    const registracia = await aiKurzyService.createRegistracia(req.body);
    res.status(201).json({ data: registracia });
  } catch (error) {
    next(error);
  }
};

export const updateRegistracia = async (req, res, next) => {
  try {
    const { registraciaId } = req.params;
    const registracia = await aiKurzyService.updateRegistracia(parseInt(registraciaId), req.body);
    res.json({ data: registracia });
  } catch (error) {
    next(error);
  }
};

export const deleteRegistracia = async (req, res, next) => {
  try {
    const { registraciaId } = req.params;
    const result = await aiKurzyService.deleteRegistracia(parseInt(registraciaId));
    res.json({ data: result });
  } catch (error) {
    next(error);
  }
};

// ==================== COMBINED TABLE (Excel-style) ====================

export const getCombinedTable = async (req, res, next) => {
  try {
    const data = await aiKurzyService.getCombinedTableData();
    res.json({ data });
  } catch (error) {
    next(error);
  }
};

export const updateField = async (req, res, next) => {
  try {
    const { registraciaId } = req.params;
    const { field, value } = req.body;
    const result = await aiKurzyService.updateField(parseInt(registraciaId), field, value);
    res.json({ data: result });
  } catch (error) {
    next(error);
  }
};

// ==================== PRILOHY (Documents) ====================

export const getPrilohy = async (req, res, next) => {
  try {
    const { registraciaId } = req.params;
    const prilohy = await aiKurzyService.getPrilohyByRegistracia(parseInt(registraciaId));
    res.json({ data: prilohy });
  } catch (error) {
    next(error);
  }
};

export const uploadPriloha = async (req, res, next) => {
  try {
    const { registraciaId } = req.params;
    const file = req.file;

    if (!file) {
      return res.status(400).json({ message: 'Súbor je povinný' });
    }

    const priloha = await aiKurzyService.createPriloha({
      registraciaId: parseInt(registraciaId),
      nazovSuboru: file.originalname,
      typPrilohy: req.body.typPrilohy || 'ine',
      cestaKSuboru: file.path,
      mimeType: file.mimetype,
      velkostSuboru: file.size,
      popis: req.body.popis || null,
    });

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

export const deletePriloha = async (req, res, next) => {
  try {
    const { prilohaId } = req.params;
    const result = await aiKurzyService.deletePriloha(parseInt(prilohaId));

    // Optionally delete the file from disk
    if (result.filePath) {
      const fs = await import('fs/promises');
      try {
        await fs.unlink(result.filePath);
      } catch {
        // File might not exist, ignore
      }
    }

    res.json({ data: { success: true } });
  } catch (error) {
    next(error);
  }
};

export const downloadPriloha = async (req, res, next) => {
  try {
    const { prilohaId } = req.params;
    const priloha = await aiKurzyService.getPrilohaById(parseInt(prilohaId));

    if (!priloha) {
      return res.status(404).json({ success: false, error: { message: 'Príloha nenájdená' } });
    }

    const fs = await import('fs/promises');
    try {
      await fs.access(priloha.cestaKSuboru);
    } catch {
      return res.status(404).json({ success: false, error: { message: 'Súbor nenájdený na serveri' } });
    }

    res.download(priloha.cestaKSuboru, priloha.nazovSuboru);
  } catch (error) {
    next(error);
  }
};

// ==================== STATISTICS ====================

export const getStats = async (req, res, next) => {
  try {
    const stats = await aiKurzyService.getKurzyStats();
    res.json({ data: stats });
  } catch (error) {
    next(error);
  }
};

// ==================== CERTIFICATE ====================

export const generateCertificate = async (req, res, next) => {
  try {
    const { registraciaId } = req.params;
    const { templateName } = req.body;
    const { generateCertificate: generateCert } = await import('../services/ai-kurzy/certificate.service.js');

    const result = await generateCert(parseInt(registraciaId), templateName || 'AIcertifikat');

    res.status(201).json({
      data: result,
      message: 'Certifikát bol vygenerovaný',
    });
  } catch (error) {
    next(error);
  }
};
