import { api as apiClient } from '../auth/http';

export interface FaydaStartResponse {
  authorizationUrl: string;
}

export interface FaydaCompleteResult {
  purpose: 'LOGIN' | 'VERIFY';
  verified: boolean;
  fullName?: string;
  email?: string;
  phoneNumber?: string;
  /** ISO yyyy-MM-dd */
  birthdate?: string;
  gender?: string;
  iamUserId?: string;
  userDataSaved?: boolean;
}

/** Message posted from the /callback popup back to the opener window. */
export interface FaydaCallbackMessage {
  type: 'fayda-callback';
  code?: string;
  state?: string;
  error?: string;
  errorDescription?: string;
}

export const verifaydaService = {
  /** Returns the eSignet authorize URL to open in a popup. */
  start: () =>
    apiClient
      .post<FaydaStartResponse>('/fayda/verification/start', {
        purpose: 'VERIFY',
        platform: 'WEB',
      })
      .then((r) => r.data),

  /** Exchange the callback code+state for the verified identity attributes. */
  complete: (code: string, state: string) =>
    apiClient
      .get<FaydaCompleteResult>(
        `/fayda/verification/complete?code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}`,
      )
      .then((r) => r.data),
};
