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

export const PARTNER_TYPES = ["ORGANIZATION", "INDIVIDUAL"] as const;

const builtins = (params: { companyType?: TailorAnyDBType; currencyType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company from organization module");
  const preferredCurrencyId = db
    .uuid({ optional: true })
    .description("Optional preferred transaction currency");
  return {
    name: db.string().description("Business partner display name"),
    type: db
      .enum(["ORGANIZATION", "INDIVIDUAL"])
      .description("Partner type: ORGANIZATION or INDIVIDUAL"),
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "businessPartners",
        })
      : companyId,
    preferredCurrencyId: params.currencyType
      ? preferredCurrencyId.relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "businessPartners",
        })
      : preferredCurrencyId,
    status: db
      .enum(businessPartnerLifecycle.states)
      .description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
  };
};

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

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

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

export const businessPartner = createBusinessPartnerType({});
