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

const builtins = (params: { companyType?: TailorAnyDBType; customerType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const customerId = db.uuid({ optional: true }).description("Optional scoped customer");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "salesPriceLists",
        })
      : companyId,
    customerId: params.customerType
      ? customerId.relation({
          type: "n-1",
          toward: { type: params.customerType },
          backward: "salesPriceLists",
        })
      : customerId,
    channelId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: 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"),
  };
};

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

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

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

export const salesPriceList = createSalesPriceListType({});
