import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { productionOrderLifecycle } from "./productionOrder.lifecycle.generated";

const builtins = (params: {
  companyType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
  itemType?: TailorAnyDBType;
}) => {
  const orderedItemId = db.uuid().description("Foreign key to Item – the item to be manufactured");
  const companyId = db.uuid().description("Foreign key to Company");
  const siteId = db.uuid().description("Foreign key to Site");
  return {
    orderedItemId: params.itemType
      ? orderedItemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "productionOrders",
        })
      : orderedItemId,
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "productionOrders",
        })
      : companyId,
    siteId: params.siteType
      ? siteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "productionOrders",
        })
      : siteId,
    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(productionOrderLifecycle.states)
      .description(
        "Lifecycle status: DRAFT, RELEASED, IN_PROGRESS, COMPLETED, TECHNICALLY_COMPLETE, CLOSED, CANCELLED",
      ),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

export function createProductionOrderType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProductionOrderTypeParams<F>,
) {
  return db
    .type("ProductionOrder", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const productionOrder = createProductionOrderType({});
