import { Router, Request, Response } from 'express';
import { PluginContext } from '../../../backend/src/core/types';

export function createFinanceRoutes(ctx: PluginContext): Router {
    const router = Router();
    const { db, hooks } = ctx;

    // GET /plans — List subscription plans
    router.get('/plans', async (_req: Request, res: Response) => {
        try {
            const plans = await db('subscription_plans').orderBy('monthly_price', 'asc');
            res.json({ plans });
        } catch (err: any) {
            res.status(500).json({ error: 'Erro ao listar planos' });
        }
    });

    // GET /invoices — List invoices (optional partner filter)
    router.get('/invoices', async (req: Request, res: Response) => {
        try {
            const partnerId = req.query.partner_id as string;
            const status = req.query.status as string;

            let query = db('invoices')
                .join('partners', 'invoices.partner_id', 'partners.id')
                .select('invoices.*', 'partners.company_name');

            if (partnerId) query = query.where({ 'invoices.partner_id': partnerId });
            if (status) query = query.where({ 'invoices.status': status });

            const invoices = await query.orderBy('invoices.due_date', 'desc');
            res.json({ invoices });
        } catch (err: any) {
            res.status(500).json({ error: 'Erro ao listar faturas' });
        }
    });

    // POST /invoices — Create invoice
    router.post('/invoices', async (req: Request, res: Response) => {
        try {
            const { partner_id, plan_id, amount, due_date } = req.body;

            const [id] = await db('invoices').insert({
                partner_id, plan_id, amount,
                issue_date: db.fn.now(),
                due_date,
                status: 'Pendente',
            });

            await hooks.emit('invoice:created', { invoiceId: id, partnerId: partner_id });
            const invoice = await db('invoices').where({ id }).first();
            res.status(201).json(invoice);
        } catch (err: any) {
            res.status(500).json({ error: 'Erro ao criar fatura' });
        }
    });

    // PUT /invoices/:id/pay — Mark invoice as paid
    router.put('/invoices/:id/pay', async (req: Request, res: Response) => {
        try {
            await db('invoices').where({ id: req.params.id }).update({
                status: 'Paga',
                paid_at: db.fn.now(),
            });
            await hooks.emit('invoice:paid', { invoiceId: req.params.id });
            res.json({ message: 'Fatura paga com sucesso' });
        } catch (err: any) {
            res.status(500).json({ error: 'Erro ao pagar fatura' });
        }
    });

    // GET /dashboard — Financial overview
    router.get('/dashboard', async (_req: Request, res: Response) => {
        try {
            const [totalRevenue] = await db('invoices')
                .where({ status: 'Paga' })
                .sum('amount as total');

            const [pendingRevenue] = await db('invoices')
                .where({ status: 'Pendente' })
                .sum('amount as total');

            const [overdueRevenue] = await db('invoices')
                .where({ status: 'Atrasada' })
                .sum('amount as total');

            const [activeSubscriptions] = await db('partners')
                .where({ status: 'active' })
                .count('id as count');

            const planDistribution = await db('partners')
                .select('subscription_plan_id as plan')
                .count('id as count')
                .where({ status: 'active' })
                .groupBy('subscription_plan_id');

            res.json({
                totalRevenue: Number(totalRevenue.total || 0),
                pendingRevenue: Number(pendingRevenue.total || 0),
                overdueRevenue: Number(overdueRevenue.total || 0),
                activeSubscriptions: Number(activeSubscriptions.count),
                planDistribution,
            });
        } catch (err: any) {
            res.status(500).json({ error: 'Erro ao buscar dashboard financeiro' });
        }
    });

    // GET /commissions — List commissions
    router.get('/commissions', async (req: Request, res: Response) => {
        try {
            const partnerId = req.query.partner_id as string;
            let query = db('commissions');
            if (partnerId) query = query.where({ partner_id: partnerId });
            const commissions = await query.orderBy('transaction_date', 'desc');
            res.json({ commissions });
        } catch (err: any) {
            res.status(500).json({ error: 'Erro ao listar comissões' });
        }
    });

    return router;
}
