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

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

export function createPurchaseOrderLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseOrderLineTypeParams<F>,
) {
  return db
    .type("PurchaseOrderLine", {
      purchaseOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseOrder },
          backward: "lines",
        })
        .description("Foreign key to PurchaseOrder"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "purchaseOrderLines",
        })
        .description("Foreign key to Item"),
      itemSnapshotName: db
        .string({ optional: true })
        .description("Snapshotted item display name at order time"),
      itemSnapshotSku: db
        .string({ optional: true })
        .description("Snapshotted item SKU at order time"),

      quantity: db.decimal().description("Ordered quantity"),
      unitPrice: db.decimal().description("Unit price"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchaseOrderLines",
        })
        .description("Unit of measure"),
      receivingSiteId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "purchaseOrderLines",
        })
        .description("Optional line-level receiving Site"),
      requiresPhysicalReceipt: db
        .bool()
        .description("Whether physical receipt is required for this line"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseOrderLine = createPurchaseOrderLineType({
  itemType: itemStub,
  unitType: unitStub,
  siteType: siteStub,
});
