import { Injectable } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { Prisma } from '@prisma/client';

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

  create(data: Prisma.SiteAttendanceEventCreateInput) {
    return this.prisma.siteAttendanceEvent.create({ data });
  }

  findByCheckpointUserAndDate(
    checkpointId: string,
    userId: string,
    localDate: string,
  ) {
    return this.prisma.siteAttendanceEvent.findMany({
      where: { checkpointId, userId, localDate },
      orderBy: { timestamp: 'asc' },
    });
  }

  findByCheckpointAndDate(
    checkpointId: string,
    localDate: string,
    page: number = 1,
    pageSize: number = 50,
  ) {
    return this.prisma.siteAttendanceEvent.findMany({
      where: { checkpointId, localDate },
      orderBy: { timestamp: 'desc' },
      skip: (page - 1) * pageSize,
      take: pageSize,
      include: {
        user: {
          select: { id: true, displayName: true, email: true },
        },
      },
    });
  }

  findAllByCheckpointAndDate(checkpointId: string, localDate: string) {
    return this.prisma.siteAttendanceEvent.findMany({
      where: { checkpointId, localDate },
      orderBy: { timestamp: 'asc' },
      select: { userId: true, eventType: true, timestamp: true },
    });
  }

  countByCheckpointAndDate(checkpointId: string, localDate: string) {
    return this.prisma.siteAttendanceEvent.count({
      where: { checkpointId, localDate },
    });
  }

  findLatestEvent(
    checkpointId: string,
    userId: string,
    eventType: string,
    sinceTimestamp: Date,
  ) {
    return this.prisma.siteAttendanceEvent.findFirst({
      where: {
        checkpointId,
        userId,
        eventType: eventType as any,
        timestamp: { gte: sinceTimestamp },
      },
      orderBy: { timestamp: 'desc' },
    });
  }
}
