const CompanyStampService = require('../../services/stamp/company/CompanyStampService');
const { logger } = require('../../middleware/logger');

exports.upload = async (req, res) => {
  try {
    const { base64, mimeType, label, activate } = req.body || {};
    if (!base64) return res.status(400).json({ error: 'Missing base64' });
    const stamp = await CompanyStampService.uploadStamp({
      user: req.user,
      base64,
      mimeType,
      label,
      activate: !!activate
    });
    res.status(201).json(stamp);
  } catch (e) {
    if (e.code === 'PRIMARY_STAMP_EXISTS') {
      return res.status(409).json({
        error: e.message,
        existing: e.existing
          ? {
              id: e.existing.id,
              company_id: e.existing.company_id,
              label: e.existing.label,
              mime_type: e.existing.mime_type,
              image_base64: e.existing.image_base64,
              is_active: e.existing.is_active,
              created_at: e.existing.created_at,
              updated_at: e.existing.updated_at
            }
          : null
      });
    }
    logger.error('CompanyStampController.upload:error', e.message);
    res.status(400).json({ error: e.message });
  }
};

exports.listMine = async (req, res) => {
  try {
    const list = await CompanyStampService.listCompanyStamps(req.user);
    res.json(list);
  } catch (e) {
    res.status(403).json({ error: e.message });
  }
};

exports.activeMine = async (req, res) => {
  try {
    const stamp = await CompanyStampService.getMyActive(req.user);
    res.json(stamp || null);
  } catch (e) {
    res.status(403).json({ error: e.message });
  }
};

exports.activate = async (req, res) => {
  try {
    const updated = await CompanyStampService.activateStamp(req.params.id, req.user);
    res.json(updated);
  } catch (e) {
    res.status(e.message === 'Not found' ? 404 : 403).json({ error: e.message });
  }
};

exports.delete = async (req, res) => {
  try {
    const ok = await CompanyStampService.deleteStamp(req.params.id, req.user);
    if (!ok) return res.status(404).json({ error: 'Not found' });
    res.status(204).end();
  } catch (e) {
    if (e.message === 'Forbidden') {
      return res.status(403).json({ error: e.message });
    }
    logger.error('CompanyStampController.delete:error', e);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

// NEW: List all company stamps (admin-only)
exports.listAll = async (req, res) => {
  try {
    const list = await CompanyStampService.listAllStamps(req.user);
    res.json(list);
  } catch (e) {
    res.status(e.message === 'Forbidden' ? 403 : 400).json({ error: e.message });
  }
};
