import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core";
import { db } from "@tailor-platform/sdk";
import { productionOrder } from "./productionOrder";
import { workCenter } from "./workCenter";
import { workOrderLifecycle } from "./workOrder.lifecycle.generated";

export function createWorkOrderType() {
  return db
    .type("WorkOrder", {
      productionOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: productionOrder },
          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: workCenter },
          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();
