import { useMutation, useQueryClient } from '@tanstack/react-query';
import { verificationApi } from '../apis';
import { verificationKeys } from '../keys';
import type { IdentityKycInput, RunStepResult } from '../types';

export interface SubmitIdentityResult {
  identity: RunStepResult;
  /** Null when identity KYC itself failed — Shahkar requires a verified national id first. */
  shahkar: RunStepResult | null;
}

/**
 * Runs the automated identity flow: national-ID + liveness KYC, then — only if that **passes** — the
 * phone↔national-id Shahkar match the server chains off the bound national id. Both are surfaced so B4
 * can show each step's outcome (incl. the handled shared-SIM Shahkar failure). Invalidates the status
 * so B3 reflects the new step states from cache. A malformed national id throws `400`; a vendor
 * mismatch is a `failed` step in the result (not a throw).
 */
export function useSubmitIdentity() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (input: IdentityKycInput): Promise<SubmitIdentityResult> => {
      const identity = await verificationApi.runIdentityKyc(input);
      const shahkar = identity.stepStatus === 'passed' ? await verificationApi.runShahkarMatch() : null;
      return { identity, shahkar };
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: verificationKeys.status() });
    },
  });
}
