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

const builtins = (params: { currencyType?: TailorAnyDBType }) => {
  const currencyId = db.uuid().description("Foreign key to Currency from primitives module");
  return {
    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: params.currencyType
      ? currencyId.relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "partnerBankAccounts",
        })
      : currencyId,
    isDefault: db.bool().description("Whether this is the default bank account for the partner"),
  };
};

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

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

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

export const partnerBankAccount = createPartnerBankAccountType({});
