import { Result } from '@shared/kernel/fp';
import { Valid } from '@registratie/domain/change-request.machine';
import { ApiClient } from '@shared/infrastructure/api-client';
import { runSubmit, SUBMIT_FAILED } from '@shared/application/submit';

/**
 * Command: POST an address change to the backend (`/api/v1/change-requests`),
 * which re-validates and returns a reference. Same shape as the other submit
 * commands — a `Result`, never a thrown error — so the form's reduce can branch.
 */
export function submitChangeRequest(client: ApiClient, data: Valid): Promise<Result<string, string>> {
  return runSubmit(async () => {
    const res = await client.changeRequests({
      straat: data.straat,
      postcode: data.postcode,
      woonplaats: data.woonplaats,
    });
    return res.referentie ?? '';
  }, SUBMIT_FAILED);
}
