import { ApprovalState, Prisma } from '@prisma/client';

export interface TicketFilter {
  errors?: string[];
  approvalStates?: ApprovalState[];
  documentInfo?: ('approval' | 'transport_document')[];
}

export function createPrismaQueryFromTicketFilters(
  filter: TicketFilter,
): Prisma.TicketWhereInput[] {
  const conditions: Prisma.TicketWhereInput[] = [];

  Object.entries(filter ?? {}).forEach(([property, args]) => {
    switch (property) {
      case 'errors':
        if (args.length > 0)
          conditions.push({
            errors: {
              hasSome: [...args],
            },
          });
        return;
      case 'approvalStates':
        if (args.length > 0)
          conditions.push({
            approvalState: {
              in: [...args],
            },
          });
        return;
      case 'documentInfo':
        if (args.includes('approval')) {
          conditions.push({
            OR: [
              {
                documentInfo: {
                  path: ['approval', 'location'],
                  not: 'company',
                },
              },
              {
                documentInfo: {
                  path: ['approval', 'location'],
                  equals: Prisma.JsonNull,
                },
              },
            ],
          });
        }
        if (args.includes('td_company')) {
          conditions.push({
            documentInfo: {
              path: ['tdLocation'],
              equals: 'company',
            },
          });
        }
        if (args.includes('td_customer')) {
          conditions.push({
            documentInfo: {
              path: ['tdLocation'],
              equals: 'customer',
            },
          });
        }
        return;
    }
  });
  return conditions;
}
