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

const builtins = (params: {
  itemType?: TailorAnyDBType;
  currencyType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
}) => {
  const itemId = db.uuid().description("Foreign key to Item");
  const currencyId = db.uuid().description("Foreign key to Currency");
  const unitId = db.uuid().description("Foreign key to Unit");
  return {
    priceListId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: purchasePriceList },
        backward: "purchasePriceRules",
      })
      .description("Foreign key to PurchasePriceList"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "purchasePriceRules",
        })
      : itemId,
    currencyId: params.currencyType
      ? currencyId.relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "purchasePriceRules",
        })
      : currencyId,
    unitId: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchasePriceRules",
        })
      : unitId,
    minimumQuantity: db.decimal().description("Minimum quantity break for this rule"),
    unitPrice: db.decimal().description("Rule price per purchase unit"),
    effectiveFrom: db.date().description("Rule effective start date"),
    effectiveTo: db.date({ optional: true }).description("Optional effective end date"),
    priority: db.int().description("Deterministic rule priority within the list"),
    status: db
      .enum(purchasePriceRuleLifecycle.states)
      .description("Lifecycle status: ACTIVE, INACTIVE"),
    notes: db.string({ optional: true }).description("Optional descriptive notes"),
  };
};

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

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

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

export const purchasePriceRule = createPurchasePriceRuleType({});
