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

export const PARTNER_ROLES = ["CUSTOMER", "SUPPLIER"] as const;

const builtins = {
  partnerId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: businessPartner },
      backward: "partnerRoles",
    })
    .description("Foreign key to BusinessPartner"),
  role: db.enum(["CUSTOMER", "SUPPLIER"]).description("Role classification: CUSTOMER or SUPPLIER"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

export interface CreatePartnerRoleTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
}

export function createPartnerRoleType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePartnerRoleTypeParams<F>,
) {
  return db
    .type("PartnerRole", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["partnerId", "role"],
      unique: true,
      name: "partner_role_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const partnerRole = createPartnerRoleType({});
