/**
 * Financial Model Routes
 *
 * Revenue forecasts, P&L statements, cash flow, unit economics, and scenario planning.
 */

import express, { Request, Response } from 'express';
import { body, validationResult } from 'express-validator';
import { getModels } from '../models';
import { authenticateJwtOrApiToken } from '../middleware/dualAuth';
import { requirePermission } from '../middleware/permissions';

const router = express.Router();

router.use(authenticateJwtOrApiToken);

// Get all financial models for a company
router.get('/:companyId', async (req: Request, res: Response) => {
  try {
    const { companyId } = req.params;
    const { FinancialModel } = getModels();

    if (!req.user!.companyIds.includes(companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const models = await FinancialModel.find({ companyId }).sort({ createdAt: -1 });
    res.json(models);
  } catch (error) {
    res.status(500).json({ error: 'Failed to get financial models' });
  }
});

// Get single financial model
router.get('/detail/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { FinancialModel } = getModels();

    const model = await FinancialModel.findById(id);
    if (!model) {
      res.status(404).json({ error: 'Financial model not found' });
      return;
    }

    if (!req.user!.companyIds.includes(model.companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    res.json(model);
  } catch (error) {
    res.status(500).json({ error: 'Failed to get financial model' });
  }
});

// Create financial model
router.post(
  '/',
  requirePermission('funding', 'create'),
  [
    body('name').trim().notEmpty().withMessage('Model name is required'),
    body('companyId').notEmpty().withMessage('Company ID is required'),
    body('startDate').notEmpty().withMessage('Start date is required'),
    body('endDate').notEmpty().withMessage('End date is required'),
  ],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        res.status(400).json({ errors: errors.array() });
        return;
      }

      if (!req.user!.companyIds.includes(req.body.companyId) && req.user!.role !== 'admin') {
        res.status(403).json({ error: 'Access denied' });
        return;
      }

      const { FinancialModel } = getModels();
      const cleanBody = Object.fromEntries(
        Object.entries(req.body).filter(([, v]) => v !== '')
      );
      const model = new FinancialModel({ ...cleanBody, createdBy: req.user!._id });
      await model.save();

      res.status(201).json(model);
    } catch (error: any) {
      console.error('[FinancialModel Create Error]', error?.message || error);
      if (error?.name === 'ValidationError') {
        const messages = Object.values(error.errors).map((e: any) => e.message);
        res.status(400).json({ error: messages.join('. '), details: error?.message });
        return;
      }
      res.status(500).json({ error: 'Failed to create financial model', details: error?.message });
    }
  }
);

// Update financial model
router.put('/:id', requirePermission('funding', 'edit'), async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { FinancialModel } = getModels();

    const model = await FinancialModel.findById(id);
    if (!model) {
      res.status(404).json({ error: 'Financial model not found' });
      return;
    }

    if (!req.user!.companyIds.includes(model.companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const cleanBody = Object.fromEntries(
      Object.entries(req.body).filter(([, v]) => v !== '')
    );
    Object.assign(model, cleanBody, { updatedAt: new Date() });
    await model.save();

    res.json(model);
  } catch (error: any) {
    console.error('[FinancialModel Update Error]', error?.message || error);
    res.status(500).json({ error: 'Failed to update financial model', details: error?.message });
  }
});

// Delete financial model
router.delete('/:id', requirePermission('funding', 'delete'), async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { FinancialModel } = getModels();

    const model = await FinancialModel.findById(id);
    if (!model) {
      res.status(404).json({ error: 'Financial model not found' });
      return;
    }

    if (!req.user!.companyIds.includes(model.companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    await FinancialModel.findByIdAndDelete(id);
    res.json({ message: 'Financial model deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete financial model' });
  }
});

// Add scenario
router.post('/:id/scenarios', requirePermission('funding', 'create'), async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { FinancialModel } = getModels();

    const model = await FinancialModel.findById(id);
    if (!model) {
      res.status(404).json({ error: 'Financial model not found' });
      return;
    }

    if (!req.user!.companyIds.includes(model.companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    model.scenarios.push(req.body);
    model.updatedAt = new Date();
    await model.save();

    res.json(model);
  } catch (error) {
    res.status(500).json({ error: 'Failed to add scenario' });
  }
});

// Set active scenario
router.put('/:id/active-scenario', requirePermission('funding', 'edit'), async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { scenarioId } = req.body;
    const { FinancialModel } = getModels();

    const model = await FinancialModel.findById(id);
    if (!model) {
      res.status(404).json({ error: 'Financial model not found' });
      return;
    }

    if (!req.user!.companyIds.includes(model.companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    model.activeScenarioId = scenarioId;
    model.updatedAt = new Date();
    await model.save();

    res.json(model);
  } catch (error) {
    res.status(500).json({ error: 'Failed to set active scenario' });
  }
});

export default router;