import { Injectable } from '@nestjs/common';
import { AttendanceRegistration } from '@prisma/client';
import { Interval } from 'date-fns';
import { PrismaService } from 'src/core/database/prisma.service';
import { AttendanceRegistrationEvents } from './attendance-registration-events.enum';

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

  async findById(
    attendanceRegistrationId: number,
  ): Promise<AttendanceRegistration> {
    return await this.prisma.attendanceRegistration.findUnique({
      where: {
        attendanceRegistrationId,
      },
    });
  }

  async findInInterval(
    interval: Interval,
    eventTypes: AttendanceRegistrationEvents[] = [
      AttendanceRegistrationEvents.ClockedIn,
      AttendanceRegistrationEvents.ClockedOut,
    ],
  ): Promise<AttendanceRegistration[]> {
    return await this.prisma.attendanceRegistration.findMany({
      where: {
        event: {
          in: eventTypes,
        },
        AND: [
          {
            dateTime: {
              gte: new Date(interval.start),
            },
          },
          {
            dateTime: {
              lt: new Date(interval.end),
            },
          },
        ],
      },
      orderBy: {
        dateTime: 'asc',
      },
    });
  }

  async findByEmployeeInInterval(
    employeeId: number,
    timeRange: Interval,
    eventTypes: AttendanceRegistrationEvents[] = [
      AttendanceRegistrationEvents.ClockedIn,
      AttendanceRegistrationEvents.ClockedOut,
    ],
  ): Promise<AttendanceRegistration[]> {
    return await this.prisma.attendanceRegistration.findMany({
      where: {
        employeeId,
        event: {
          in: eventTypes,
        },
        AND: [
          {
            dateTime: {
              gte: new Date(timeRange.start),
            },
          },
          {
            dateTime: {
              lt: new Date(timeRange.end),
            },
          },
        ],
      },
      orderBy: {
        dateTime: 'asc',
      },
    });
  }
}
