import { Inject, Injectable } from '@nestjs/common';
import { Kysely, sql } from 'kysely';
import { KYSELY_CLIENT_PROVIDER_TOKEN } from 'src/core/database/database.module';
import { DB } from 'src/core/database/types';

@Injectable()
export class ReportsRepository {
  constructor(
    @Inject(KYSELY_CLIENT_PROVIDER_TOKEN) private readonly db: Kysely<DB>,
  ) {}

  toursReport() {
    return this.db
      .selectFrom('Tour')
      .select((eb) => [
        'ordinanceType as Verordnungsart',
        sql<string>`EXTRACT(MONTH FROM "startDate")`.as('MonthNumber'),
        eb.fn.count<number>('operationId').as('TourCount'),
      ])
      .groupBy('MonthNumber')
      .groupBy('ordinanceType')
      .execute();
  }

  patientsReport() {
    return this.db
      .selectFrom('Patient')
      .select((eb) => eb.fn.countAll().as('PatientCount'))
      .execute();
  }

  employeesReport() {
    return this.db
      .selectFrom('Employee')
      .select((eb) => eb.fn.countAll().as('EmployeeCount'))
      .execute();
  }

  attendanceRegistrationsReport() {
    return this.db
      .selectFrom('AttendanceRegistration')
      .select((eb) => [
        eb.fn.countAll().as('AttendanceRegistrationCount'),
        sql<string>`EXTRACT(MONTH FROM "dateTime")`.as('MonthNumber'),
      ])
      .groupBy('MonthNumber')
      .execute();
  }

  workTimesReport() {
    return this.db
      .selectFrom('WorkTime')
      .select((eb) => [
        eb.fn.countAll().as('WorkTimeCount'),
        sql<string>`EXTRACT(MONTH FROM "startDate")`.as('MonthNumber'),
      ])
      .groupBy('MonthNumber')
      .execute();
  }

  plannedTimesReport() {
    return this.db
      .selectFrom('PlannedTime')
      .select((eb) => [
        eb.fn.countAll().as('PlannedTimeCount'),
        sql<string>`EXTRACT(MONTH FROM "startDate")`.as('MonthNumber'),
      ])
      .groupBy('MonthNumber')
      .execute();
  }
}
