import { Injectable } from '@nestjs/common';
import { PlannedTime } from '@prisma/client';
import { Interval } from 'date-fns';
import { PrismaService } from 'src/core/database/prisma.service';

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

  async findById(id: string): Promise<PlannedTime> {
    return await this.prisma.plannedTime.findUnique({
      where: { id },
    });
  }

  async findByPersonnelNumberInInterval(
    personnelNumber: string,
    interval: Interval,
  ): Promise<PlannedTime[]> {
    return await this.prisma.plannedTime.findMany({
      where: {
        userId: personnelNumber,
        AND: [
          {
            startDate: {
              gte: new Date(interval.start),
            },
          },
          {
            startDate: {
              lt: new Date(interval.end),
            },
          },
        ],
      },
    });
  }

  async findByOrdinanceTypesInInterval(
    ordinanceType: string | undefined,
    interval: Interval,
  ): Promise<PlannedTime[]> {
    const allOrdinanceTypes =
      ordinanceType == undefined || ordinanceType === 'ALL' ? true : false;
    return await this.prisma.plannedTime.findMany({
      where: {
        AND: [
          {
            startDate: {
              gte: new Date(interval.start),
            },
          },
          {
            startDate: {
              lte: new Date(interval.end),
            },
          },
          {
            AND: [
              ...(allOrdinanceTypes
                ? []
                : [
                    {
                      department: {
                        contains: ordinanceType,
                      },
                    },
                  ]),
              {
                department: {
                  not: 'Leitstelle',
                },
              },
              {
                department: {
                  not: 'Büro',
                },
              },
              {
                department: {
                  not: 'Fortbildung',
                },
              },
            ],
          },
          {
            note: null,
          },
          {
            userId: {
              not: '0',
            },
          },
        ],
      },
    });
  }
}
