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 { purchaseChangeOrder } from "./purchaseChangeOrder";
import { purchaseOrderLine } from "./purchaseOrderLine";

export const CHANGE_ORDER_LINE_ACTIONS: [string, string, string] = ["ADD", "MODIFY", "REMOVE"];

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

export function createPurchaseChangeOrderLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseChangeOrderLineTypeParams<F>,
) {
  return db
    .type("PurchaseChangeOrderLine", {
      purchaseChangeOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseChangeOrder },
          backward: "lines",
        })
        .description("Foreign key to PurchaseChangeOrder"),
      action: db.enum(CHANGE_ORDER_LINE_ACTIONS).description("Change action type"),
      originalPurchaseOrderLineId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: purchaseOrderLine },
          backward: "changeOrderLines",
        })
        .description("Foreign key to the original PurchaseOrderLine being modified or removed"),
      itemId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "purchaseChangeOrderLines",
        })
        .description("Foreign key to Item"),
      quantity: db
        .decimal({ optional: true })
        .description("Ordered quantity — required for ADD/MODIFY, null for REMOVE"),
      unitPrice: db
        .decimal({ optional: true })
        .description("Unit price — required for ADD/MODIFY, null for REMOVE"),
      unitId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchaseChangeOrderLines",
        })
        .description("Optional unit"),
      receivingSiteId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "purchaseChangeOrderLines",
        })
        .description("Optional line-level receiving Site"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

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