import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub, site as siteStub, item as itemStub } from "../lib/_db_deps";

export const BASE_PRODUCTION_ORDER_STATUSES = [
  "DRAFT",
  "RELEASED",
  "IN_PROGRESS",
  "COMPLETED",
  "TECHNICALLY_COMPLETE",
  "CLOSED",
  "CANCELLED",
] as const;

export interface CreateProductionOrderTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType: TailorAnyDBType;
  siteType: TailorAnyDBType;
  itemType: TailorAnyDBType;
}

export function createProductionOrderType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProductionOrderTypeParams<F>,
) {
  return db
    .type("ProductionOrder", {
      orderedItemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "productionOrders",
        })
        .description("Foreign key to Item – the item to be manufactured"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "productionOrders",
        })
        .description("Foreign key to Company"),
      siteId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "productionOrders",
        })
        .description("Foreign key to Site"),
      plannedQuantity: db
        .float()
        .description("Planned production quantity, must be greater than 0"),
      plannedStartDate: db.datetime().description("Planned start date for the production order"),
      plannedEndDate: db.datetime().description("Planned end date for the production order"),
      selectedBomVersionId: db
        .uuid({ optional: true })
        .description("Optional reference to BillOfMaterial – resolved at release"),
      selectedRoutingRevisionId: db
        .uuid({ optional: true })
        .description("Optional reference to Routing – resolved at release"),
      status: db
        .enum([...BASE_PRODUCTION_ORDER_STATUSES] as [string, ...string[]])
        .description(
          "Lifecycle status: DRAFT, RELEASED, IN_PROGRESS, COMPLETED, TECHNICALLY_COMPLETE, CLOSED, CANCELLED",
        ),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productionOrder = createProductionOrderType({
  companyType: companyStub,
  siteType: siteStub,
  itemType: itemStub,
});
