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

export interface CreateBillOfMaterialLineTypeParams {
  billOfMaterialType: TailorAnyDBType;
  itemType: TailorAnyDBType;
}

export function createBillOfMaterialLineType(params: CreateBillOfMaterialLineTypeParams) {
  return db
    .type("BillOfMaterialLine", {
      billOfMaterialId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.billOfMaterialType },
          backward: "billOfMaterialLines",
        })
        .description("Foreign key to BillOfMaterial"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "bomLineReferences",
        })
        .description("Foreign key to Item – component item"),
      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(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const billOfMaterialLine = createBillOfMaterialLineType({
  billOfMaterialType: billOfMaterial,
  itemType: itemStub,
});
