import {
  CloneEstimateSchema,
  CreateEstimateExportSchema,
  CreateEstimatePlanningHandoffSchema,
  CreateEstimateSchema,
  PermissionKey,
  UpdateEstimateDraftSchema,
} from "@capakraken/shared";
import {
  cloneEstimateRecord,
  createEstimateExportRecord,
  createEstimatePlanningHandoffRecord,
  createEstimateRecord,
  lookupDemandLineRateForEstimate,
  lookupDemandLineRateInputSchema,
  updateEstimateDraftRecord,
} from "./estimate-procedure-support.js";
import {
  controllerProcedure,
  createTRPCRouter,
  managerProcedure,
  requirePermission,
} from "../trpc.js";
import { estimateCommercialProcedures } from "./estimate-commercial.js";
import { estimatePhasingProcedures } from "./estimate-phasing.js";
import { estimateReadProcedures } from "./estimate-read.js";
import { estimateVersionWorkflowProcedures } from "./estimate-version-workflow.js";

export const estimateRouter = createTRPCRouter({
  ...estimateReadProcedures,
  ...estimateCommercialProcedures,
  ...estimatePhasingProcedures,
  ...estimateVersionWorkflowProcedures,

  create: managerProcedure
    .input(CreateEstimateSchema)
    .mutation(async ({ ctx, input }) => {
      requirePermission(ctx, PermissionKey.MANAGE_PROJECTS);
      return createEstimateRecord(ctx, input);
    }),

  clone: managerProcedure
    .input(CloneEstimateSchema)
    .mutation(async ({ ctx, input }) => {
      requirePermission(ctx, PermissionKey.MANAGE_PROJECTS);
      return cloneEstimateRecord(ctx, input);
    }),

  updateDraft: managerProcedure
    .input(UpdateEstimateDraftSchema)
    .mutation(async ({ ctx, input }) => {
      requirePermission(ctx, PermissionKey.MANAGE_PROJECTS);
      return updateEstimateDraftRecord(ctx, input);
    }),

  createExport: managerProcedure
    .input(CreateEstimateExportSchema)
    .mutation(async ({ ctx, input }) => {
      requirePermission(ctx, PermissionKey.MANAGE_PROJECTS);
      return createEstimateExportRecord(ctx, input);
    }),

  createPlanningHandoff: managerProcedure
    .input(CreateEstimatePlanningHandoffSchema)
    .mutation(async ({ ctx, input }) => {
      requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
      return createEstimatePlanningHandoffRecord(ctx, input);
    }),

  lookupDemandLineRate: controllerProcedure
    .input(lookupDemandLineRateInputSchema)
    .query(({ ctx, input }) => lookupDemandLineRateForEstimate(ctx, input)),
});
