import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { businessPartner } from "./businessPartner";

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

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

export function createPartnerRoleType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePartnerRoleTypeParams<F>,
) {
  return db
    .type("PartnerRole", {
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["partnerId", "role"],
      unique: true,
      name: "partner_role_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const partnerRole = createPartnerRoleType({});
