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

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

  async getStats(userId?: string) {
    if (!userId) {
      const totalCylinders = await this.prisma.cylinders.count();
      const cylindersInside = await this.prisma.cylinders.count({ where: { status: 'INSIDE' } });
      const cylindersOutside = await this.prisma.cylinders.count({ where: { status: 'OUTSIDE' } });
      return { totalCylinders, cylindersInside, cylindersOutside, movementsToday: 0 };
    }

    const user = await this.prisma.users.findUnique({
      where: { id: userId },
      select: { warehouseId: true, role: true },
    });

    const cylinderWhere: any = {};
    if (user?.role === AccountType.PLANT) {
      cylinderWhere.OR = [
        { warehouseId: user.warehouseId },
        {
          claim_status: false,
          status: CylinderStatus.NEW,
        },
      ];
    } else if (user?.warehouseId) {
      cylinderWhere.warehouseId = user.warehouseId;
    }

    const totalCylinders = await this.prisma.cylinders.count({ where: cylinderWhere });
    const cylindersInside = await this.prisma.cylinders.count({
      where: {
        AND: [
          cylinderWhere,
          { status: 'INSIDE' }
        ]
      },
    });
    const cylindersOutside = await this.prisma.cylinders.count({
      where: {
        AND: [
          cylinderWhere,
          { status: 'OUTSIDE' }
        ]
      },
    });

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    const movementsToday = await this.prisma.cylinder_logs.count({
      where: {
        cylinder: {
          warehouseId: user?.warehouseId || undefined, // Filter cylinder logs by warehouseId
        },
        scannedAt: {
          gte: today,
          lt: tomorrow,
        },
      },
    });

    return {
      totalCylinders,
      cylindersInside,
      cylindersOutside,
      movementsToday,
    };
  }

  async getManufacturerStats(userId: string) {
    const totalCylinders = await this.prisma.cylinders.count({
      where: { manufacturer_id: userId },
    });

    const claimedCylinders = await this.prisma.cylinders.count({
      where: {
        manufacturer_id: userId,
        claim_status: true,
      },
    });

    const leftCylinders = totalCylinders - claimedCylinders;

    return {
      totalCylinders,
      claimedCylinders,
      leftCylinders,
    };
  }
}
