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 BOM_TYPES = ["MANUFACTURE", "PHANTOM", "KIT"] as const;
export const BASE_BOM_STATUSES = ["DRAFT", "ACTIVE", "INACTIVE"] as const;

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

export function createBillOfMaterialType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateBillOfMaterialTypeParams<F>,
) {
  return db
    .type("BillOfMaterial", {
      parentItemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "billOfMaterials",
        })
        .description("Foreign key to Item – the parent/finished item"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "billOfMaterials",
        })
        .description("Foreign key to Company"),
      siteId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "billOfMaterials",
        })
        .description("Optional foreign key to Site – site scope"),
      bomType: db
        .enum([...BOM_TYPES] as [string, ...string[]])
        .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([...BASE_BOM_STATUSES] as [string, ...string[]])
        .description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

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