import {
  db,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { productionOrder } from "./productionOrder";
import { workCenter } from "./workCenter";

export const BASE_WORK_ORDER_STATUSES = [
  "PENDING",
  "IN_PROGRESS",
  "PAUSED",
  "COMPLETE",
  "CANCELLED",
] as const;

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([...BASE_WORK_ORDER_STATUSES] as [string, ...string[]])
        .description("Lifecycle status: PENDING, IN_PROGRESS, PAUSED, COMPLETE, CANCELLED"),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

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