import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { businessPartner as businessPartnerStub, company as companyStub } from "../lib/_db_deps";

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

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 ?? companyStub },
          backward: "purchasePriceLists",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType ?? businessPartnerStub },
          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(PURCHASE_PRICE_LIST_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 purchasePriceList = createPurchasePriceListType({});
