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

export interface CreateRoutingOperationTypeParams {
  routingType: TailorAnyDBType;
  workCenterType: TailorAnyDBType;
}

export function createRoutingOperationType(params: CreateRoutingOperationTypeParams) {
  return db
    .type("RoutingOperation", {
      routingId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.routingType },
          backward: "routingOperations",
        })
        .description("Foreign key to Routing"),
      sequenceNumber: db.int().description("Step order within the routing"),
      operationDescription: db
        .string({ optional: true })
        .description("Human-readable description of the operation"),
      workCenterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.workCenterType },
          backward: "routingOperations",
        })
        .description("Foreign key to WorkCenter"),
      standardSetupTime: db.float().description("Standard setup time (>= 0)"),
      standardRunTime: db.float().description("Standard run time per unit (>= 0)"),
      operatorInstructions: db
        .string({ optional: true })
        .description("Free-text instructions for the operator"),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["routingId", "sequenceNumber"],
      unique: true,
      name: "routing_operation_routing_seq_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const routingOperation = createRoutingOperationType({
  routingType: routing,
  workCenterType: workCenter,
});
