import { ShiftRotation, ShiftRotationDay, ShiftRotationDayShift } from '../../../business/models/shiftManagement/shiftRotation';
import { ShiftRotationDAO } from '../../dataAccessObjects/shiftManagement/shiftRotation';
import { ShiftRotationDayDAO } from '../../dataAccessObjects/shiftManagement/shiftRotationDay';
import { ShiftRotationDayShiftDAO } from '../../dataAccessObjects/shiftManagement/shiftRotationDayShift';

export const shiftRotationDayShiftDAOToShiftRotationDayShift = (dao: ShiftRotationDayShiftDAO): ShiftRotationDayShift => {
    return new ShiftRotationDayShift({
        createdAt: dao.createdAt,
        id: dao.id,
        instanceId: dao.instanceId,
        shiftCode: dao.shiftCode,
        shiftRotationDayId: dao.shiftRotationDayId,
        updatedAt: dao.updatedAt,
    });
};

export const shiftRotationDayDAOToShiftRotationDay = (dao: ShiftRotationDayDAO, shiftsOverride?: ShiftRotationDayShift[]): ShiftRotationDay => {
    const shifts =
        shiftsOverride ?? [...(dao.shifts ?? [])].sort((a, b) => a.id.localeCompare(b.id)).map(shiftRotationDayShiftDAOToShiftRotationDayShift);
    return new ShiftRotationDay({
        createdAt: dao.createdAt,
        dayPosition: dao.dayPosition,
        id: dao.id,
        instanceId: dao.instanceId,
        shiftRotationId: dao.shiftRotationId,
        shifts,
        type: dao.type,
        updatedAt: dao.updatedAt,
    });
};

interface ShiftRotationHeader {
    id: string;
    instanceId: number;
    name: string;
    description: string | null;
    createdAt: Date;
    updatedAt: Date;
    deletedAt?: Date | null;
}

export const buildShiftRotation = (header: ShiftRotationHeader, days: ShiftRotationDay[]): ShiftRotation => {
    return new ShiftRotation({
        createdAt: header.createdAt,
        days,
        deletedAt: header.deletedAt ?? null,
        description: header.description,
        id: header.id,
        instanceId: header.instanceId,
        name: header.name,
        updatedAt: header.updatedAt,
    });
};

export const shiftRotationDAOToShiftRotation = (dao: ShiftRotationDAO, daysOverride?: ShiftRotationDay[]): ShiftRotation => {
    const days = daysOverride ?? (dao.days ?? []).map((d) => shiftRotationDayDAOToShiftRotationDay(d)).sort((a, b) => a.dayPosition - b.dayPosition);
    return buildShiftRotation(dao, days);
};
