import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBType } from "@tailor-platform/sdk";
import { billOfMaterial } from "./billOfMaterial";

export interface CreateBillOfMaterialLineTypeParams {
  itemType?: TailorAnyDBType;
}

export function createBillOfMaterialLineType(params: CreateBillOfMaterialLineTypeParams) {
  const itemId = db.uuid().description("Foreign key to Item – component item");
  return db
    .type("BillOfMaterialLine", {
      billOfMaterialId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: billOfMaterial },
          backward: "billOfMaterialLines",
        })
        .description("Foreign key to BillOfMaterial"),
      itemId: params.itemType
        ? itemId.relation({
            type: "n-1",
            toward: { type: params.itemType },
            backward: "bomLineReferences",
          })
        : itemId,
      requiredQuantity: db.float().description("Required quantity, must be greater than 0"),
      unitOfMeasure: db.string({ optional: true }).description("Compatible unit of measure"),
      scrapAssumption: db.float({ optional: true }).description("Scrap assumption percentage"),
      isSubassembly: db
        .bool({ optional: true })
        .description("Whether this component is a subassembly"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const billOfMaterialLine = createBillOfMaterialLineType({});
