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

export const BOM_TYPES = ["MANUFACTURE", "PHANTOM", "KIT"] as const;

const builtins = (params: {
  companyType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
  itemType?: TailorAnyDBType;
}) => {
  const parentItemId = db.uuid().description("Foreign key to Item – the parent/finished item");
  const companyId = db.uuid().description("Foreign key to Company");
  const siteId = db
    .uuid({ optional: true })
    .description("Optional foreign key to Site – site scope");
  return {
    parentItemId: params.itemType
      ? parentItemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "billOfMaterials",
        })
      : parentItemId,
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "billOfMaterials",
        })
      : companyId,
    siteId: params.siteType
      ? siteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "billOfMaterials",
        })
      : siteId,
    bomType: db.enum(BOM_TYPES).description("BOM type: MANUFACTURE, PHANTOM, KIT"),
    effectivityStartDate: db.datetime({ optional: true }).description("Effectivity start date"),
    effectivityEndDate: db.datetime({ optional: true }).description("Effectivity end date"),
    defaultSelection: db.bool({ optional: true }).description("Default selection flag"),
    revisionNumber: db.string({ optional: true }).description("Revision number"),
    status: db
      .enum(billOfMaterialLifecycle.states)
      .description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
  };
};

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

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

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

export const billOfMaterial = createBillOfMaterialType({});
