import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub, currency as currencyStub } from "../lib/_db_deps";

export const BASE_PARTNER_STATUSES = ["DRAFT", "ACTIVE", "INACTIVE"] as const;

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

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

export function createBusinessPartnerType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateBusinessPartnerTypeParams<F>,
) {
  const statuses = [...BASE_PARTNER_STATUSES, ...(params.additionalStatuses ?? [])] as [
    string,
    ...string[],
  ];

  return db
    .type("BusinessPartner", {
      name: db.string().description("Business partner display name"),
      type: db
        .enum(["ORGANIZATION", "INDIVIDUAL"])
        .description("Partner type: ORGANIZATION or INDIVIDUAL"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "businessPartners",
        })
        .description("Foreign key to Company from organization module"),
      preferredCurrencyId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.currencyType ?? currencyStub },
          backward: "businessPartners",
        })
        .description("Optional preferred transaction currency"),
      status: db.enum(statuses).description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const businessPartner = createBusinessPartnerType({});
