import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { channel } from "./channel";
import { salesPriceList } from "./salesPriceList";
import { salesPriceRuleLifecycle } from "./salesPriceRule.lifecycle.generated";

const builtins = (params: {
  itemType?: TailorAnyDBType;
  customerType?: TailorAnyDBType;
  currencyType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
}) => {
  const itemId = db.uuid().description("Foreign key to Item");
  const customerId = db.uuid({ optional: true }).description("Optional scoped customer");
  const currencyId = db.uuid().description("Foreign key to Currency");
  const unitId = db.uuid().description("Foreign key to Unit");
  return {
    salesPriceListId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: salesPriceList },
        backward: "salesPriceRules",
      })
      .description("Foreign key to SalesPriceList"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "salesPriceRules",
        })
      : itemId,
    customerId: params.customerType
      ? customerId.relation({
          type: "n-1",
          toward: { type: params.customerType },
          backward: "salesPriceRules",
        })
      : customerId,
    channelId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: channel },
        backward: "salesPriceRules",
      })
      .description("Optional scoped channel"),
    currencyId: params.currencyType
      ? currencyId.relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "salesPriceRules",
        })
      : currencyId,
    unitId: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "salesPriceRules",
        })
      : unitId,
    minimumQuantity: db.float().description("Minimum quantity break"),
    unitPrice: db.float().description("Rule unit price"),
    effectiveFrom: db.date({ optional: true }).description("Optional effective start date"),
    effectiveTo: db.date({ optional: true }).description("Optional effective end date"),
    priority: db.int().description("Rule tie-break priority"),
    status: db.enum(salesPriceRuleLifecycle.states).description("Rule lifecycle status"),
    notes: db.string({ optional: true }).description("Optional notes"),
  };
};

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

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

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

export const salesPriceRule = createSalesPriceRuleType({});
