import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { businessPartner as businessPartnerStub, company as companyStub } from "../lib/_db_deps";
import { purchasePriceListLifecycle } from "./purchasePriceList.lifecycle.generated";

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

export function createPurchasePriceListType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchasePriceListTypeParams<F>,
) {
  return db
    .type("PurchasePriceList", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "purchasePriceLists",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType },
          backward: "purchasePriceLists",
        })
        .description("Foreign key to supplier BusinessPartner"),
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchasePriceList = createPurchasePriceListType({
  companyType: companyStub,
  supplierType: businessPartnerStub,
});
