import { getCsrfToken } from '@shared/api/csrf'
import { tokenStore, refreshAccessToken } from '@shared/api/tokenStore'

export interface KycResponse {
  status: boolean
  error: string
  link: string
  user_token: string
  client_user_token: string
  qr_code: string
}

const KYC_API_URL = 'https://app.kyc.elcsa.ru'

export function kycCreate(): Promise<KycResponse> {
  return doKycRequest(true)
}

async function doKycRequest(allowRetry: boolean): Promise<KycResponse> {
  const csrf = await getCsrfToken()

  const res = await fetch(`${KYC_API_URL}/kyc/create`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrf,
    },
    body: JSON.stringify({}),
  })

  if (res.status === 401 && allowRetry) {
    try {
      await refreshAccessToken()
      return doKycRequest(false)
    } catch {
      tokenStore.clear()
      throw new Error('Unauthorized')
    }
  }

  const data = await res.json()
  if (!res.ok) throw data
  return data as KycResponse
}
