import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { purchaseOrder } from "./purchaseOrder";

const builtins = (params: {
  itemType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
}) => {
  const itemId = db.uuid().description("Foreign key to Item");
  const unitId = db.uuid().description("Unit of measure");
  const receivingSiteId = db
    .uuid({ optional: true })
    .description("Optional line-level receiving Site");
  return {
    purchaseOrderId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: purchaseOrder },
        backward: "lines",
      })
      .description("Foreign key to PurchaseOrder"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "purchaseOrderLines",
        })
      : itemId,
    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: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchaseOrderLines",
        })
      : unitId,
    receivingSiteId: params.siteType
      ? receivingSiteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "purchaseOrderLines",
        })
      : receivingSiteId,
    requiresPhysicalReceipt: db
      .bool()
      .description("Whether physical receipt is required for this line"),
    billedQuantity: db
      .decimal({ optional: true })
      .description("Current billed quantity projection from external billing sources"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

export function createPurchaseOrderLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseOrderLineTypeParams<F>,
) {
  return db
    .type("PurchaseOrderLine", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseOrderLine = createPurchaseOrderLineType({});
