import { db, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { productionOrder } from "./productionOrder";
import { workCenter } from "./workCenter";
import { workOrderLifecycle } from "./workOrder.lifecycle.generated";

export interface CreateWorkOrderTypeParams {
  productionOrderType: TailorAnyDBType;
  workCenterType: TailorAnyDBType;
}

export function createWorkOrderType(params: CreateWorkOrderTypeParams) {
  return db
    .type("WorkOrder", {
      productionOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.productionOrderType },
          backward: "workOrders",
        })
        .description("Foreign key to ProductionOrder"),
      routingOperationSequenceNumber: db
        .int()
        .description("Sequence number of the routing operation"),
      workCenterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.workCenterType },
          backward: "workOrders",
        })
        .description("Foreign key to WorkCenter"),
      plannedQuantity: db.float().description("Planned quantity to produce, must be >= 0"),
      completedQuantity: db.float().description("Completed quantity, must be >= 0"),
      scrapQuantity: db.float().description("Scrap quantity, must be >= 0"),
      actualSetupTime: db.float().description("Actual setup time in minutes, must be >= 0"),
      actualRunTime: db.float().description("Actual run time in minutes, must be >= 0"),
      actualStartDate: db.datetime({ optional: true }).description("Actual start date and time"),
      pauseReason: db.string({ optional: true }).description("Reason for pausing the work order"),
      executionNotes: db.string({ optional: true }).description("Free-form notes about execution"),
      status: db
        .enum(workOrderLifecycle.states)
        .description("Lifecycle status: PENDING, IN_PROGRESS, PAUSED, COMPLETE, CANCELLED"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const workOrder = createWorkOrderType({
  productionOrderType: productionOrder,
  workCenterType: workCenter,
});
