import { Prisma, TicketValidationState } from '@prisma/client';
import { Interval } from 'date-fns';

export interface TourAccountingFilterDto {
  deviation?: 'pos' | 'neg' | 'both'[];
  missing?: 'information' | 'documents'[];
  dateRange?: Interval;
}

export function createPrismaQueryFromAccountingFilters(
  filter: TourAccountingFilterDto,
): Prisma.TourWhereInput[] {
  const conditions: Prisma.TourWhereInput[] = [];

  Object.entries(filter ?? {}).forEach(([property, args]) => {
    switch (property) {
      case 'deviation':
        if (args.includes('pos'))
          conditions.push({
            revenueDeviation: { gt: 0 },
          });
        else if (args.includes('neg'))
          conditions.push({
            revenueDeviation: { lt: 0 },
          });
        else if (args.includes('both'))
          conditions.push({
            revenueDeviation: { not: 0 },
          });
        return;
      case 'missing':
        if (args.includes('information'))
          conditions.push({
            Ticket: {
              currentState: {
                in: [
                  TicketValidationState.CREATED,
                  TicketValidationState.USER_INTERACTION_REQUIRED,
                ],
              },
            },
          });
        else if (args.includes('documents'))
          conditions.push({
            Ticket: {
              currentState: {
                in: [
                  TicketValidationState.TD_UNCERTAIN,
                  TicketValidationState.DOCUMENTS_MISSING,
                ],
              },
            },
          });
        return;
      case 'dateRange':
        conditions.push({
          AND: [
            { startDate: { gte: new Date(args.from) } },
            { startDate: { lt: new Date(args.to) } },
          ],
        });
        return;
    }
  });
  return conditions;
}
