import { Injectable } from '@nestjs/common';
import { AvicennaTenant, CostType, Tariff, TariffGroup } from '@prisma/client';
import { PrismaService } from 'src/core/database/prisma.service';

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

  async findTenant(
    healthInsurance: string,
    ordinanceType: string,
  ): Promise<AvicennaTenant> {
    return await this.prisma.avicennaTenant.findFirst({
      where: {
        OR: [
          {
            name: healthInsurance,
          },
          {
            name: {
              contains: healthInsurance,
            },
          },
        ],
        tariffGroups: {
          some: {
            ordinanceType,
          },
        },
      },
    });
  }

  async findByTariffGroupDescription(
    description: string,
    ordinanceType: string,
    dateValid: Date,
  ): Promise<Tariff & { tariffGroup: TariffGroup; costTypes: CostType[] }> {
    return await this.prisma.tariff.findFirst({
      where: {
        tariffGroup: {
          description: {
            contains: description,
          },
          ordinanceType,
        },
        OR: [
          {
            AND: [
              { validTo: null },
              {
                validFrom: {
                  lte: dateValid,
                },
              },
            ],
          },
          {
            AND: [
              { validTo: { gte: dateValid } },
              { validFrom: { lte: dateValid } },
            ],
          },
        ],
      },
      include: {
        tariffGroup: true,
        costTypes: true,
      },
    });
  }

  async findByTenantId(
    tenantId: string,
    ordinanceType: string,
    dateValid: Date,
  ): Promise<Tariff & { tariffGroup: TariffGroup; costTypes: CostType[] }> {
    return await this.prisma.tariff.findFirst({
      where: {
        tariffGroup: {
          tenants: {
            some: {
              id: tenantId,
            },
          },
          ordinanceType,
        },
        OR: [
          {
            AND: [
              { validTo: null },
              {
                validFrom: {
                  lte: dateValid,
                },
              },
            ],
          },
          {
            AND: [
              { validTo: { gte: dateValid } },
              { validFrom: { lte: dateValid } },
            ],
          },
        ],
      },
      include: {
        tariffGroup: true,
        costTypes: true,
      },
    });
  }
}
