import { Router } from 'express';
import { z } from 'zod';
import db from '../db/index.js';
import { HttpError } from '../middleware/errorHandler.js';

const router = Router();

const Schema = z.object({
  nom:                  z.string().min(1),
  type:                 z.enum(['compte_courant', 'pea_pme']).default('compte_courant'),
  investisseur_id:      z.number().int().positive().nullable().optional(),
  banque:               z.string().nullable().optional(),
  exoneration_fiscale:  z.enum(['aucune', 'pfnl_5ans']).default('aucune'),
});

router.get('/', (req, res) => {
  const rows = db.prepare(`
    SELECT c.id, c.nom, c.type, c.banque, c.exoneration_fiscale, c.investisseur_id, c.created_at,
           inv.nom AS investisseur_nom, inv.prenom AS investisseur_prenom,
           inv.type AS investisseur_type, inv.type_fiscal AS investisseur_type_fiscal
    FROM comptes c
    LEFT JOIN investisseurs inv ON inv.id = c.investisseur_id
    WHERE c.user_id = ?
    ORDER BY c.nom
  `).all(req.user.id);
  res.json(rows);
});

router.post('/', (req, res, next) => {
  try {
    const body = Schema.parse(req.body);
    const r = db.prepare(
      'INSERT INTO comptes (user_id, nom, type, banque, investisseur_id, exoneration_fiscale) VALUES (?,?,?,?,?,?)'
    ).run(req.user.id, body.nom, body.type, body.banque || null, body.investisseur_id ?? null, body.exoneration_fiscale ?? 'aucune');
    res.status(201).json({ id: r.lastInsertRowid, ...body });
  } catch (e) { next(e); }
});

router.put('/:id', (req, res, next) => {
  try {
    const body = Schema.parse(req.body);
    const r = db.prepare(
      `UPDATE comptes SET nom=?, type=?, banque=?, investisseur_id=?, exoneration_fiscale=?, updated_at=datetime('now') WHERE id=? AND user_id=?`
    ).run(body.nom, body.type, body.banque || null, body.investisseur_id ?? null, body.exoneration_fiscale ?? 'aucune', req.params.id, req.user.id);
    if (r.changes === 0) throw new HttpError(404, 'Not found');
    res.json({ id: Number(req.params.id), ...body });
  } catch (e) { next(e); }
});

router.delete('/:id', (req, res, next) => {
  try {
    const r = db.prepare('DELETE FROM comptes WHERE id=? AND user_id=?')
      .run(req.params.id, req.user.id);
    if (r.changes === 0) throw new HttpError(404, 'Not found');
    res.status(204).end();
  } catch (e) { next(e); }
});

export default router;
