import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { currency as currencyStub, item as itemStub, unit as unitStub } from "../lib/_db_deps";
import { purchasePriceList } from "./purchasePriceList";

export const PURCHASE_PRICE_RULE_STATUSES: [string, string] = ["ACTIVE", "INACTIVE"];

export interface CreatePurchasePriceRuleTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  priceListType?: TailorAnyDBType;
  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: params.priceListType ?? purchasePriceList },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to PurchasePriceList"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType ?? itemStub },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to Item"),
      currencyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.currencyType ?? currencyStub },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to Currency"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType ?? unitStub },
          backward: "purchasePriceRules",
        })
        .description("Foreign key to Unit"),
      minimumQuantity: db.float().description("Minimum quantity break for this rule"),
      unitPrice: db.float().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(PURCHASE_PRICE_RULE_STATUSES)
        .description("Lifecycle status: ACTIVE, INACTIVE"),
      notes: db.string({ optional: true }).description("Optional descriptive notes"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchasePriceRule = createPurchasePriceRuleType({});
