import { PermissionKey, ShiftProjectSchema } from "@capakraken/shared";
import { emitProjectShifted } from "../sse/event-bus.js";
import { createTRPCRouter, managerProcedure, requirePermission } from "../trpc.js";
import { timelineAllocationMutationProcedures } from "./timeline-allocation-mutations.js";
import { timelineReadProcedures } from "./timeline-read.js";
import { loadProjectShiftContext } from "./timeline-project-load-support.js";
import { applyTimelineProjectShift } from "./timeline-shift-support.js";

export const timelineRouter = createTRPCRouter({
  ...timelineReadProcedures,
  ...timelineAllocationMutationProcedures,

  /**
   * Apply a project shift: validate, then commit all allocation date changes.
   * Reads includeSaturday from each allocation's metadata.
   */
  applyShift: managerProcedure
    .input(ShiftProjectSchema)
    .mutation(async ({ ctx, input }) => {
      requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
      const { projectId, newStartDate, newEndDate } = input;
      const context = await loadProjectShiftContext(ctx.db, projectId);
      const result = await applyTimelineProjectShift({
        db: ctx.db,
        projectId,
        newStartDate,
        newEndDate,
        context,
      });

      emitProjectShifted(result.event);

      return {
        project: result.project,
        validation: result.validation,
      };
    }),
});
