import {
  db,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { purchaseRequisition } from "./purchaseRequisition";
import { purchaseRequisitionLine } from "./purchaseRequisitionLine";
import { purchaseOrder } from "./purchaseOrder";
import { purchaseOrderLine } from "./purchaseOrderLine";

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()
        .relation({
          type: "n-1",
          toward: { type: purchaseOrderLine },
          backward: "requisitionLineAllocations",
        })
        .description("Foreign key to generated PurchaseOrderLine"),
      allocatedQuantity: db
        .decimal()
        .description("Quantity allocated from the requisition line to the PO line"),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchaseRequisitionLineAllocation = createPurchaseRequisitionLineAllocationType();
