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 { channel } from "./channel";
import { salesPriceListLifecycle } from "./salesPriceList.lifecycle.generated";

export interface CreateSalesPriceListTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  customerType?: TailorAnyDBType;
  channelType?: TailorAnyDBType;
}

export function createSalesPriceListType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesPriceListTypeParams<F>,
) {
  return db
    .type("SalesPriceList", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "salesPriceLists",
        })
        .description("Foreign key to Company"),
      customerId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.customerType ?? businessPartnerStub },
          backward: "salesPriceLists",
        })
        .description("Optional scoped customer"),
      channelId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.channelType ?? channel },
          backward: "salesPriceLists",
        })
        .description("Optional scoped channel"),
      name: db.string().description("Price-list name"),
      code: db.string({ optional: true }).description("Optional price-list code"),
      priority: db.int().description("List precedence priority"),
      status: db.enum(salesPriceListLifecycle.states).description("Price-list lifecycle status"),
      notes: db.string({ optional: true }).description("Optional notes"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const salesPriceList = createSalesPriceListType({});
