import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { item as itemStub, unit as unitStub } from "../lib/_db_deps";
import { goodsReceipt } from "./goodsReceipt";
import { purchaseOrderLine } from "./purchaseOrderLine";

export interface CreateGoodsReceiptLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  itemType: TailorAnyDBType;
  unitType: TailorAnyDBType;
}

export function createGoodsReceiptLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateGoodsReceiptLineTypeParams<F>,
) {
  return db
    .type("GoodsReceiptLine", {
      goodsReceiptId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: goodsReceipt },
          backward: "lines",
        })
        .description("Foreign key to GoodsReceipt"),
      purchaseOrderLineId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: purchaseOrderLine },
          backward: "goodsReceiptLines",
        })
        .description("Foreign key to PurchaseOrderLine (nullable for receipts without a PO)"),
      itemId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "goodsReceiptLines",
        })
        .description("Optional Item (defaults to PurchaseOrderLine item)"),
      quantity: db.decimal().description("Received quantity on this line"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "goodsReceiptLines",
        })
        .description("Unit of measure"),
      requiresInventoryHandoff: db
        .bool()
        .description("Whether this line triggers an inventory handoff"),
      destinationSite: db
        .string({ optional: true })
        .description("Destination site for inventory handoff"),
      destinationStorageLocation: db
        .string({ optional: true })
        .description("Destination storage location for inventory handoff"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const goodsReceiptLine = createGoodsReceiptLineType({
  itemType: itemStub,
  unitType: unitStub,
});
