import { prisma } from "../../core/prisma";
import { AppError } from "../../core/AppError";

export const dashboardService = {

    async getLiveStats(shopId: string) {

        const session = await prisma.cashSession.findFirst({
            where: {
                shopId,
                status: "OPEN"
            },
            include: {
                orders: {
                    include: {
                        payments: true,
                        orderItems: {
                            include: {
                                product: {
                                    include: {
                                        station: true
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });

        if (!session) {
            throw new AppError("No open session", 400);
        }

        const revenue = session.orders.reduce(
            (sum, o) => sum + o.total,
            0
        );

        const payments = session.orders.flatMap(o => o.payments);

        const cash = payments
            .filter(p => p.method === "CASH")
            .reduce((sum, p) => sum + p.amount, 0);

        const card = payments
            .filter(p => p.method === "CARD")
            .reduce((sum, p) => sum + p.amount, 0);

        const sumup = payments
            .filter(p => p.provider === "SUMUP")
            .reduce((sum, p) => sum + p.amount, 0);

        const draft = session.orders.filter(o => o.status === "DRAFT").length;
        const paid = session.orders.filter(o => o.status === "PAID").length;
        const partiallyPaid = session.orders.filter(o => o.status === "PARTIALLY_PAID").length;

        // 📊 Stations stats
        const stationMap: Record<string, any> = {};

        session.orders.forEach(order => {
            order.orderItems.forEach(item => {
                const station = item.product.station;

                if(!station) {
                    throw new AppError("Station not found", 404);
                }

                if (!stationMap[station.id]) {
                    stationMap[station.id] = {
                        stationId: station.id,
                        name: station.name,
                        pending: 0,
                        preparing: 0,
                        ready: 0
                    };
                }

                if (item.status === "PENDING") stationMap[station.id].pending++;
                if (item.status === "PREPARING") stationMap[station.id].preparing++;
                if (item.status === "READY") stationMap[station.id].ready++;
            });
        });

        return {
            session,
            totals: {
                revenue,
                cash,
                card,
                sumup
            },
            orders: {
                draft,
                paid,
                partiallyPaid
            },
            stations: Object.values(stationMap)
        };
    }
};