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

export const LINE_STATUSES: [string, string] = ["ACTIVE", "SUPERSEDED"];

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"),
      description: db.string({ optional: true }).description("Optional line description"),
      quantity: db.decimal().description("Ordered quantity"),
      unitPrice: db.decimal().description("Unit price"),
      unitId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchaseOrderLines",
        })
        .description("Optional unit"),
      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"),
      matchedPriceRuleId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: purchasePriceRule },
          backward: "purchaseOrderLines",
        })
        .description("Optional matched PurchasePriceRule"),
      revisionNumber: db
        .int({ optional: true })
        .description("PO revision in which this line became active"),
      lineStatus: db
        .enum(LINE_STATUSES, { optional: true })
        .description("Whether this line is the current active version or has been superseded"),
      supersededByLineId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "supersedes",
        })
        .description("Pointer to the replacement line when superseded"),
      rootLineId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "lineageDescendants",
        })
        .description("Pointer to the original v1 line in this lineage chain, null for v1 lines"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

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