import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { OrderStatus, ReminderStatus } from '@prisma/client';

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

  async getStats(tenantId: string) {
    const now = new Date();
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    const todayStart = new Date(); todayStart.setHours(0, 0, 0, 0);
    const todayEnd = new Date(); todayEnd.setHours(23, 59, 59, 999);

    const [
      totalClients,
      openOrders,
      inProgressOrders,
      doneOrders,
      overdueReminders,
      todayReminders,
      revenueThisMonth,
      overdueClients,
      todayClients,
    ] = await Promise.all([
      this.prisma.client.count({ where: { tenantId, isActive: true } }),
      this.prisma.serviceOrder.count({ where: { tenantId, status: OrderStatus.OPEN } }),
      this.prisma.serviceOrder.count({ where: { tenantId, status: OrderStatus.IN_PROGRESS } }),
      this.prisma.serviceOrder.count({ where: { tenantId, status: OrderStatus.DONE } }),
      this.prisma.reminder.count({ where: { tenantId, status: ReminderStatus.OVERDUE } }),
      this.prisma.reminder.count({
        where: { tenantId, status: ReminderStatus.PENDING, nextMaintenanceDate: { gte: todayStart, lte: todayEnd } },
      }),
      this.prisma.serviceOrder.aggregate({
        where: { tenantId, status: OrderStatus.DONE, completedAt: { gte: startOfMonth } },
        _sum: { value: true },
      }),
      this.prisma.reminder.findMany({
        where: { tenantId, status: 'OVERDUE' },
        include: { client: { select: { id: true, name: true, phone: true, whatsapp: true } } },
        orderBy: { nextMaintenanceDate: 'asc' },
        take: 10,
      }),
      this.prisma.reminder.findMany({
        where: { tenantId, status: 'PENDING', nextMaintenanceDate: { gte: todayStart, lte: todayEnd } },
        include: { client: { select: { id: true, name: true, phone: true, whatsapp: true } } },
        take: 10,
      }),
    ]);

    return {
      stats: {
        totalClients,
        openOrders,
        inProgressOrders,
        doneOrders,
        overdueReminders,
        todayReminders,
        revenueThisMonth: Number(revenueThisMonth._sum.value ?? 0),
      },
      overdueClients,
      todayClients,
    };
  }

  async getMonthlyRevenue(tenantId: string, year: number) {
    const data = [];
    for (let month = 0; month < 12; month++) {
      const start = new Date(year, month, 1);
      const end = new Date(year, month + 1, 0, 23, 59, 59);
      const result = await this.prisma.serviceOrder.aggregate({
        where: { tenantId, status: 'DONE', completedAt: { gte: start, lte: end } },
        _sum: { value: true },
        _count: true,
      });
      data.push({
        month: month + 1,
        revenue: Number(result._sum.value ?? 0),
        orders: result._count,
      });
    }
    return data;
  }
}
