import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class DashboardService {
    constructor(private prisma: PrismaService) { }

    /**
     * Get Financial KPIs
     * - GMV (Gross Merchandise Value) = Sum of all order totals
     * - Net Revenue = Sum of marketplace fees
     * - Pending Payouts = Sum of pending withdrawals
     * - Orders counts by status
     */
    async getKpis() {
        const now = new Date();
        const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

        // GMV - Sum of paid orders
        const gmvResult = await this.prisma.$queryRaw<[{ total: bigint }]>`
            SELECT COALESCE(SUM(total_cents), 0) as total 
            FROM orders 
            WHERE status IN ('Pago', 'Faturado', 'Entregue')
            AND created_at >= ${startOfMonth}
        `;
        const gmvCents = Number(gmvResult[0]?.total || 0);

        // Net Revenue (12% of GMV as commission - simplified)
        const netRevenueCents = Math.floor(gmvCents * 0.12);

        // Pending Payouts
        const pendingPayoutsResult = await this.prisma.$queryRaw<[{ total: bigint }]>`
            SELECT COALESCE(SUM(amount_cents), 0) as total 
            FROM withdrawals 
            WHERE status = 'pending'
        `;
        const pendingPayoutsCents = Number(pendingPayoutsResult[0]?.total || 0);

        // Order counts by status
        const orderCountsResult = await this.prisma.$queryRaw<{ status: string; count: bigint }[]>`
            SELECT status, COUNT(*) as count 
            FROM orders 
            GROUP BY status
        `;
        const orderCounts = orderCountsResult.reduce((acc, row) => {
            acc[row.status] = Number(row.count);
            return acc;
        }, {} as Record<string, number>);

        // Active companies (using raw SQL to avoid Prisma schema differences)
        const companiesResult = await this.prisma.$queryRaw<[{ count: bigint }]>`
            SELECT COUNT(*) as count FROM companies WHERE is_verified = true
        `;
        const companiesCount = Number(companiesResult[0]?.count || 0);

        return {
            gmv_cents: gmvCents,
            net_revenue_cents: netRevenueCents,
            pending_payouts_cents: pendingPayoutsCents,
            order_counts: orderCounts,
            active_companies: companiesCount,
            period: 'month_to_date',
        };
    }

    /**
     * Get daily revenue data for charts (last 30 days)
     */
    async getRevenueChart() {
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

        const revenueData = await this.prisma.$queryRaw<{ date: Date; total: bigint }[]>`
            SELECT DATE(created_at) as date, SUM(total_cents) as total
            FROM orders
            WHERE status IN ('Pago', 'Faturado', 'Entregue')
            AND created_at >= ${thirtyDaysAgo}
            GROUP BY DATE(created_at)
            ORDER BY date ASC
        `;

        return revenueData.map((row) => ({
            date: row.date.toISOString().split('T')[0],
            gmv_cents: Number(row.total),
            revenue_cents: Math.floor(Number(row.total) * 0.12),
        }));
    }
}
