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

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

export function createPartnerBankAccountType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePartnerBankAccountTypeParams<F>,
) {
  return db
    .type("PartnerBankAccount", {
      partnerId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: businessPartner },
          backward: "partnerBankAccounts",
        })
        .description("Foreign key to BusinessPartner"),
      bankName: db.string().description("Name of the bank"),
      accountHolderName: db.string().description("Name of the account holder"),
      accountNumber: db.string({ optional: true }).description("Bank account number"),
      routingNumber: db.string({ optional: true }).description("Domestic routing number"),
      iban: db.string({ optional: true }).description("International Bank Account Number"),
      swiftBic: db
        .string({ optional: true })
        .description("SWIFT/BIC code for international transfers"),
      currencyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.currencyType ?? currencyStub },
          backward: "partnerBankAccounts",
        })
        .description("Foreign key to Currency from primitives module"),
      isDefault: db.bool().description("Whether this is the default bank account for the partner"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const partnerBankAccount = createPartnerBankAccountType({});
