import { Router } from 'express';
import db from '../db/index.js';

const router = Router();

/* GET /api/pfu — liste triée par année */
router.get('/', (req, res) => {
  const rows = db.prepare('SELECT * FROM taux_pfu ORDER BY annee ASC').all();
  res.json(rows);
});

/* POST /api/pfu — ajouter une année */
router.post('/', (req, res) => {
  const { annee, impot_revenu, csg, crds, solidarite } = req.body;
  if (!annee || impot_revenu == null || csg == null || crds == null || solidarite == null) {
    return res.status(400).json({ error: 'Champs requis : annee, impot_revenu, csg, crds, solidarite' });
  }
  const prelev_sociaux = Number(csg) + Number(crds) + Number(solidarite);
  const pfu_total      = Number(impot_revenu) + prelev_sociaux;
  try {
    const stmt = db.prepare(
      'INSERT INTO taux_pfu (annee, pfu_total, impot_revenu, prelev_sociaux, csg, crds, solidarite) VALUES (?, ?, ?, ?, ?, ?, ?)'
    );
    const result = stmt.run(
      Number(annee), pfu_total, Number(impot_revenu), prelev_sociaux,
      Number(csg), Number(crds), Number(solidarite)
    );
    res.status(201).json(db.prepare('SELECT * FROM taux_pfu WHERE id = ?').get(result.lastInsertRowid));
  } catch (e) {
    if (e.message?.includes('UNIQUE')) return res.status(409).json({ error: `L'année ${annee} existe déjà.` });
    throw e;
  }
});

/* PUT /api/pfu/:id — modifier */
router.put('/:id', (req, res) => {
  const { annee, impot_revenu, csg, crds, solidarite } = req.body;
  if (!annee || impot_revenu == null || csg == null || crds == null || solidarite == null) {
    return res.status(400).json({ error: 'Champs requis : annee, impot_revenu, csg, crds, solidarite' });
  }
  const prelev_sociaux = Number(csg) + Number(crds) + Number(solidarite);
  const pfu_total      = Number(impot_revenu) + prelev_sociaux;
  try {
    db.prepare(
      `UPDATE taux_pfu SET annee=?, pfu_total=?, impot_revenu=?, prelev_sociaux=?,
       csg=?, crds=?, solidarite=?, updated_at=datetime('now') WHERE id=?`
    ).run(
      Number(annee), pfu_total, Number(impot_revenu), prelev_sociaux,
      Number(csg), Number(crds), Number(solidarite), Number(req.params.id)
    );
    const row = db.prepare('SELECT * FROM taux_pfu WHERE id = ?').get(Number(req.params.id));
    if (!row) return res.status(404).json({ error: 'Introuvable' });
    res.json(row);
  } catch (e) {
    if (e.message?.includes('UNIQUE')) return res.status(409).json({ error: `L'année ${annee} existe déjà.` });
    throw e;
  }
});

/* DELETE /api/pfu/:id */
router.delete('/:id', (req, res) => {
  db.prepare('DELETE FROM taux_pfu WHERE id = ?').run(Number(req.params.id));
  res.status(204).end();
});

export default router;
