import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import { BankAccountNotFoundError } from "../lib/errors.generated";

export interface SetDefaultPartnerBankAccountInput {
  id: string;
}

/**
 * Function: setDefaultPartnerBankAccount
 *
 * Sets a bank account as the default for a partner, unsetting the
 * previous default.
 */
export async function run(
  db: Transaction,
  input: SetDefaultPartnerBankAccountInput,
  _ctx: CommandContext,
) {
  const { id } = input;

  // 1. Check account exists
  const account = await db
    .selectFrom("PartnerBankAccount")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!account) {
    return err(new BankAccountNotFoundError(id));
  }

  // 2. Unset isDefault on all other accounts for same partner
  await db
    .updateTable("PartnerBankAccount")
    .set({ isDefault: false })
    .where("partnerId", "=", account.partnerId)
    .where("id", "!=", id)
    .execute();

  // 3. Set isDefault on this account
  const updated = await db
    .updateTable("PartnerBankAccount")
    .set({ isDefault: true })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ bankAccount: updated });
}
