import { FindAttributeOptions, Includeable, literal, WhereOptions } from 'sequelize';
import { ShiftDAO } from '../../../../dataAccessObjects/shiftManagement/shift';
import { ShiftAssignedShiftDAO } from '../../../../dataAccessObjects/shiftManagement/shiftAssignedShifts';
import { ShiftAssignedTimeSlotDAO } from '../../../../dataAccessObjects/shiftManagement/shiftAssignedTimeSlot';
import { ShiftTimeSlotDAO } from '../../../../dataAccessObjects/shiftManagement/shiftTimeSlot';

export const getShiftInclude = (
    where?: WhereOptions,
    required = false,
    attributes?: FindAttributeOptions,
    excludeTimeSlots?: boolean,
): Includeable => ({
    as: 'shift',
    attributes,
    include: excludeTimeSlots
        ? []
        : [
              {
                  model: ShiftTimeSlotDAO,
                  required: false,
              },
          ],
    model: ShiftDAO,
    on: literal(`
      "shiftAssociations"."shiftCode"   = "shiftAssociations->shift"."code" AND
      "shiftAssociations"."shiftVersion"= "shiftAssociations->shift"."version"
    `),
    required,
    where,
});

export const getShiftAssignedShiftInclude = ({
    assignedShiftsWhere,
    assignedShiftsRequired,
    shiftWhere,
    shiftRequired,
    options,
}: {
    assignedShiftsWhere?: WhereOptions;
    assignedShiftsRequired?: boolean;
    shiftWhere?: WhereOptions;
    shiftRequired?: boolean;
    options?: {
        shiftAssignedShiftsAttributes?: FindAttributeOptions;
        shiftAttributes?: FindAttributeOptions;
        excludeTimeSlots?: boolean;
    };
} = {}): Includeable[] => [
    {
        as: 'shiftAssociations',
        attributes: options?.shiftAssignedShiftsAttributes,
        include: [
            ...(options?.excludeTimeSlots
                ? [getShiftInclude(shiftWhere, shiftRequired, options?.shiftAttributes, options?.excludeTimeSlots)]
                : [
                      {
                          model: ShiftAssignedTimeSlotDAO,
                          required: false,
                      },
                      getShiftInclude(shiftWhere, shiftRequired, options?.shiftAttributes, options?.excludeTimeSlots),
                  ]),
        ],
        model: ShiftAssignedShiftDAO,
        required: assignedShiftsRequired,
        where: assignedShiftsWhere,
    },
];
