import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core";
import { db } from "@tailor-platform/sdk";
import { purchaseOrder } from "./purchaseOrder";
import { purchaseRequisition } from "./purchaseRequisition";
import { purchaseRequisitionLine } from "./purchaseRequisitionLine";

export function createPurchaseRequisitionLineAllocationType() {
  return db
    .type("PurchaseRequisitionLineAllocation", {
      purchaseRequisitionId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseRequisition },
          backward: "lineAllocations",
        })
        .description("Foreign key to source PurchaseRequisition"),
      purchaseRequisitionLineId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseRequisitionLine },
          backward: "allocations",
        })
        .description("Foreign key to source PurchaseRequisitionLine"),
      purchaseOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseOrder },
          backward: "requisitionLineAllocations",
        })
        .description("Foreign key to generated PurchaseOrder"),
      purchaseOrderLineId: db
        .uuid()
        .description(
          "ID of the generated PurchaseOrderLine (no FK constraint — line may be removed by amendment)",
        ),
      allocatedQuantity: db
        .decimal()
        .description("Quantity allocated from the requisition line to the PO line"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseRequisitionLineAllocation = createPurchaseRequisitionLineAllocationType();
