const taxService = require('../../services/tax/taxService');

function resolveActorUserId(req) {
  const raw = req.user?.id ?? req.user?.user_id ?? req.body?.userId ?? req.body?.user_id;
  if (raw == null) return null;
  const num = Number(raw);
  return Number.isNaN(num) ? null : num;
}

module.exports = {
  async getAllVatRates(req, res) {
    try {
      const data = await taxService.listCurrentRates();
      return res.json({ success: true, data });
    } catch (err) {
      console.error('[GET VAT RATES]', err);
      return res.status(500).json({ success: false, message: err.message });
    }
  },

  async importVatRatesCsv(req, res) {
    try {
      if (!req.file || !req.file.buffer) {
        return res.status(400).json({ success: false, message: 'CSV file required' });
      }
      const entries = taxService.parseCsv(req.file.buffer);
      const actorUserId = resolveActorUserId(req);
      const summary = await taxService.importRates(entries, actorUserId);
      return res.json({ success: true, summary });
    } catch (err) {
      console.error('[IMPORT VAT RATES]', err);
      return res.status(400).json({ success: false, message: err.message });
    }
  },

  async getVatHistory(req, res) {
    try {
      const countryCode = req.params.countryCode.toUpperCase();
      const result = await taxService.getHistory(countryCode);
      return res.json({ success: true, data: result });
    } catch (err) {
      console.error('[GET VAT HISTORY]', err);
      return res.status(400).json({ success: false, message: err.message });
    }
  }
};
