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

const builtins = (params: {
  itemType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
  suggestedSupplierType?: TailorAnyDBType;
}) => {
  const itemId = db.uuid().description("Foreign key to Item");
  const unitId = db.uuid().description("Unit of measure");
  const suggestedSupplierId = db
    .uuid({ optional: true })
    .description("Optional suggested supplier");
  return {
    purchaseRequisitionId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: purchaseRequisition },
        backward: "lines",
      })
      .description("Foreign key to PurchaseRequisition"),
    description: db.string().description("Line description (required, supports free-text)"),
    quantity: db.decimal().description("Requested quantity"),
    estimatedUnitPrice: db.decimal().description("Estimated unit price"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "purchaseRequisitionLines",
        })
      : itemId,
    unitId: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchaseRequisitionLines",
        })
      : unitId,
    suggestedSupplierId: params.suggestedSupplierType
      ? suggestedSupplierId.relation({
          type: "n-1",
          toward: { type: params.suggestedSupplierType },
          backward: "purchaseRequisitionLines",
        })
      : suggestedSupplierId,
    needByDate: db.date({ optional: true }).description("Optional need-by date for this line"),
  };
};

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

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

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

export const purchaseRequisitionLine = createPurchaseRequisitionLineType({});
