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

const builtins = (params: { companyType?: TailorAnyDBType; supplierType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const supplierId = db.uuid().description("Foreign key to supplier BusinessPartner");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "purchasePriceLists",
        })
      : companyId,
    supplierId: params.supplierType
      ? supplierId.relation({
          type: "n-1",
          toward: { type: params.supplierType },
          backward: "purchasePriceLists",
        })
      : supplierId,
    name: db.string().description("Price-list display name"),
    code: db.string({ optional: true }).description("Optional price-list code"),
    priority: db.int().description("Deterministic list priority within supplier scope"),
    status: db
      .enum(purchasePriceListLifecycle.states)
      .description("Lifecycle status: ACTIVE, INACTIVE"),
    notes: db.string({ optional: true }).description("Optional descriptive notes"),
  };
};

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

export interface CreatePurchasePriceListTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
  companyType?: TailorAnyDBType;
  supplierType?: TailorAnyDBType;
}

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

export const purchasePriceList = createPurchasePriceListType({});
