import { Router } from 'express';
import { z } from 'zod';
import db from '../db/index.js';
import { HttpError } from '../middleware/errorHandler.js';
import { requireInvestisseur } from '../middleware/investisseurScope.js';
import { generateSimulWithReinvestissements } from '../utils/schedule.js';

const router = Router();
router.use(requireInvestisseur);

const Schema = z.object({
  investissement_id: z.number().int().positive(),
  montant:           z.number().positive(),
  date_reinvestissement: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
  note:              z.string().optional().nullable(),
});

/** Vérifie que l'investissement appartient bien à l'utilisateur connecté. */
function checkOwnership(investissementId, userId) {
  const row = db.prepare(`
    SELECT i.id FROM investissements i
    JOIN investisseurs inv ON inv.id = i.investisseur_id AND inv.user_id = ?
    WHERE i.id = ?
  `).get(userId, investissementId);
  if (!row) throw new HttpError(404, 'Investissement introuvable');
  return row;
}

// GET /api/reinvestissements?investissement_id=X  (un investissement)
// GET /api/reinvestissements?scope=all             (tous les investissements de l'utilisateur)
router.get('/', (req, res, next) => {
  try {
    if (req.query.scope === 'all') {
      const rows = db.prepare(`
        SELECT rv.*
        FROM reinvestissements rv
        JOIN investissements i ON i.id = rv.investissement_id
        JOIN investisseurs inv ON inv.id = i.investisseur_id AND inv.user_id = ?
        ORDER BY rv.date_reinvestissement
      `).all(req.user.id);
      return res.json(rows);
    }

    const invId = Number(req.query.investissement_id);
    if (!invId) throw new HttpError(400, 'investissement_id requis');
    checkOwnership(invId, req.user.id);

    const rows = db.prepare(
      'SELECT * FROM reinvestissements WHERE investissement_id = ? ORDER BY date_reinvestissement'
    ).all(invId);
    res.json(rows);
  } catch (e) { next(e); }
});

// POST /api/reinvestissements
router.post('/', (req, res, next) => {
  try {
    const body = Schema.parse(req.body);
    checkOwnership(body.investissement_id, req.user.id);

    const r = db.prepare(`
      INSERT INTO reinvestissements (investissement_id, montant, date_reinvestissement, note)
      VALUES (?, ?, ?, ?)
    `).run(body.investissement_id, body.montant, body.date_reinvestissement, body.note || null);

    // Régénérer le tableau de simulation en tenant compte du réinvestissement
    generateSimulWithReinvestissements(db, body.investissement_id);

    res.status(201).json({ id: r.lastInsertRowid, ...body });
  } catch (e) { next(e); }
});

// DELETE /api/reinvestissements/:id
router.delete('/:id', (req, res, next) => {
  try {
    const row = db.prepare('SELECT * FROM reinvestissements WHERE id = ?').get(req.params.id);
    if (!row) throw new HttpError(404, 'Réinvestissement introuvable');
    checkOwnership(row.investissement_id, req.user.id);

    db.prepare('DELETE FROM reinvestissements WHERE id = ?').run(req.params.id);

    // Régénérer le tableau de simulation sans ce réinvestissement
    generateSimulWithReinvestissements(db, row.investissement_id);

    res.status(204).end();
  } catch (e) { next(e); }
});

export default router;
