import { useAuthStore } from '@/stores/auth'

import {
  createEveningDetectiveServerClient,
  type EveningDetectiveServer,
} from './generated/crabs/evening_detective_server'
import { createHttpHandler } from './generated/crabs/evening_detective_server/client'

export function getAuthClient() {
  const authStore = useAuthStore()
  return buildAuthClient(authStore.refreshTokenAction, authStore.getToken)
}

function buildAuthClient(
  refreshTokens: () => Promise<boolean>,
  getToken: () => string | null,
): EveningDetectiveServer {
  return createEveningDetectiveServerClient(
    createAuthHttpHandler(refreshTokens, createHttpHandler(getToken)),
  )
}

function createAuthHttpHandler(
  refreshTokens: () => Promise<boolean>,
  handler: (request: { path: string; method: string; body: string | null }) => Promise<unknown>,
): (request: { path: string; method: string; body: string | null }) => Promise<unknown> {
  return async (request: { path: string; method: string; body: string | null }) => {
    try {
      return await handler(request)
    } catch {
      await refreshTokens()
      return await handler(request)
    }
  }
}
