import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { currency as currencyStub, item as itemStub, unit as unitStub } from "../lib/_db_deps";
import { purchasePriceList } from "./purchasePriceList";
import { purchasePriceRuleLifecycle } from "./purchasePriceRule.lifecycle.generated";

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

export function createPurchasePriceRuleType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchasePriceRuleTypeParams<F>,
) {
  return db
    .type("PurchasePriceRule", {
      priceListId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchasePriceList },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to PurchasePriceList"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to Item"),
      currencyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to Currency"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to Unit"),
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchasePriceRule = createPurchasePriceRuleType({
  itemType: itemStub,
  currencyType: currencyStub,
  unitType: unitStub,
});
