import {
  buildSplitAllocationReadModel,
  type SplitAssignmentRecord,
  type SplitDemandRequirementRecord,
} from "@capakraken/application";
import type { ShiftInput } from "@capakraken/engine";
import type { WeekdayAvailability } from "@capakraken/shared";

export interface TimelineShiftWindow {
  id: string;
  resourceId: string;
  projectId: string;
  startDate: Date | string;
  endDate: Date | string;
  hoursPerDay: number;
  status: string;
}

export interface BuildTimelineShiftPlanInput {
  demandRequirements: SplitDemandRequirementRecord[];
  assignments: SplitAssignmentRecord[];
  allAssignmentWindows: TimelineShiftWindow[];
}

export interface TimelineShiftPlan {
  validationAllocations: ShiftInput["allocations"];
}

export function buildTimelineShiftPlan({
  demandRequirements,
  assignments,
  allAssignmentWindows,
}: BuildTimelineShiftPlanInput): TimelineShiftPlan {
  const readModel = buildSplitAllocationReadModel({
    demandRequirements,
    assignments,
  });

  const validationAllocations = readModel.assignments
    .filter((assignment) => assignment.resourceId !== null && assignment.resource)
    .map((assignment) => {
      const metadata = (assignment.metadata as Record<string, unknown> | null | undefined) ?? {};

      return {
        ...assignment,
        resource: {
          ...assignment.resource!,
          availability: assignment.resource!.availability as WeekdayAvailability,
        },
        allAllocationsForResource: allAssignmentWindows.filter(
          (window) => window.resourceId === assignment.resourceId,
        ),
        includeSaturday: (metadata.includeSaturday as boolean | undefined) ?? false,
      };
    }) as unknown as ShiftInput["allocations"];

  return {
    validationAllocations,
  };
}
