import { clientFetch } from '@/lib/api/client';
import { unwrap, type ApiEnvelope } from '@/lib/api/types';
import { normalizeSheba, shebaBankName } from '../iban';
import type { AddBankAccountInput, NurseBankAccountDto, NurseBankAccountsApi } from '../types';

const BASE = '/api/v1/nurse_bank_accounts';

/**
 * Real HTTP implementation of the NurseBankAccountsApi seam (b3 action-style routes). `add`
 * runs the ownership inquiry server-side and returns the account with `matchedNationalId`
 * already set, so the real path needs no polling. Selected once USE_NURSE_BANK_MOCK is false.
 */
export const nurseBankClientApi: NurseBankAccountsApi = {
  list: async () => unwrap(await clientFetch<ApiEnvelope<NurseBankAccountDto[]>>(`${BASE}/list`)),

  add: async (input: AddBankAccountInput) => {
    const iban = normalizeSheba(input.iban);
    return unwrap(
      await clientFetch<ApiEnvelope<NurseBankAccountDto>>(`${BASE}/add`, {
        method: 'POST',
        body: JSON.stringify({ bankName: shebaBankName(iban), accountHolderName: input.accountHolderName, iban }),
      }),
    );
  },

  setPrimary: async (id: number) => {
    await clientFetch<ApiEnvelope<void>>(`${BASE}/set_primary/${id}`, { method: 'POST' });
  },

  verifyOwnership: async (id: number) =>
    unwrap(await clientFetch<ApiEnvelope<NurseBankAccountDto>>(`${BASE}/verify_ownership/${id}`, { method: 'POST' })),
};
