import { getAnonymizationDirectory } from "../lib/anonymization.js";
import {
  loadTimelineProjectContextDetailArtifacts,
} from "./timeline-project-context-support.js";
import {
  buildTimelineProjectContextDetailResponse,
  buildTimelineProjectContextResponse,
} from "./timeline-project-context-response-support.js";
import { loadTimelineProjectContext } from "./timeline-project-load-support.js";

type TimelineProjectContextProcedureDb =
  & Parameters<typeof getAnonymizationDirectory>[0]
  & Parameters<typeof loadTimelineProjectContext>[0]
  & Parameters<typeof loadTimelineProjectContextDetailArtifacts>[0];

export async function readTimelineProjectContextResponse(
  db: TimelineProjectContextProcedureDb,
  projectId: string,
) {
  const {
    project,
    allocations,
    demands,
    assignments,
    allResourceAllocations,
    resourceIds,
  } = await loadTimelineProjectContext(db, projectId);
  const directory = await getAnonymizationDirectory(db);

  return buildTimelineProjectContextResponse({
    project,
    allocations,
    demands,
    assignments,
    allResourceAllocations,
    resourceIds,
    directory,
  });
}

export async function readTimelineProjectContextDetailResponse(
  db: TimelineProjectContextProcedureDb,
  input: {
    projectId: string;
    startDate?: string | undefined;
    endDate?: string | undefined;
    durationDays?: number | undefined;
  },
) {
  const projectContext = await loadTimelineProjectContext(db, input.projectId);
  const directory = await getAnonymizationDirectory(db);
  const { period, holidayOverlays, assignmentConflicts } =
    await loadTimelineProjectContextDetailArtifacts(db, {
      projectId: input.projectId,
      requestedStartDate: input.startDate,
      requestedEndDate: input.endDate,
      durationDays: input.durationDays,
      projectStartDate: projectContext.project.startDate,
      projectEndDate: projectContext.project.endDate,
      firstAssignmentStartDate: projectContext.assignments[0]?.startDate,
      firstDemandStartDate: projectContext.demands[0]?.startDate,
      assignments: projectContext.assignments,
      allResourceAllocations: projectContext.allResourceAllocations,
      resourceIds: projectContext.resourceIds,
    });

  return buildTimelineProjectContextDetailResponse({
    project: projectContext.project,
    period,
    allocations: projectContext.allocations,
    demands: projectContext.demands,
    assignments: projectContext.assignments,
    allResourceAllocations: projectContext.allResourceAllocations,
    resourceIds: projectContext.resourceIds,
    assignmentConflicts,
    holidayOverlays,
    directory,
  });
}
