import type { HTTPMethod } from 'h3'

// Custom OpenAPI fetch client that wraps useRequestFetch. This ensures that authentication headers
// are forwarded correctly during SSR. Unlike fetch, useRequestFetch returns data directly,
// so we need to wrap it to mimic the Response object.
export const wrappedFetchWrap = (requestFetch: ReturnType<typeof useRequestFetch>) =>
  async function wrappedFetch(url: string, init?: RequestInit): Promise<Response> {
    try {
      // Convert RequestInit to $fetch options
      const fetchOptions: Parameters<typeof $fetch>[1] = {
        method: (init?.method || 'GET') as HTTPMethod,
        headers: init?.headers as Record<string, string>
      }

      if (init?.body) {
        fetchOptions.body = init.body
      }

      // Use $fetch to get the data with proper header forwarding
      const data = await requestFetch(url, fetchOptions)

      // Create a proper Response object
      return new Response(JSON.stringify(data), {
        status: 200,
        statusText: 'OK',
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error: unknown) {
      console.error('Fetch error:', error)

      // Check if it's a FetchError from ofetch
      if (error && typeof error === 'object' && 'status' in error) {
        const fetchError = error as { status?: number; statusText?: string; data?: unknown; message?: string }

        const status = fetchError.status || 500
        const statusText = fetchError.statusText || fetchError.message || 'Internal Server Error'
        const errorData = fetchError.data || fetchError.message || 'Unknown error'

        return new Response(JSON.stringify(errorData), {
          status,
          statusText,
          headers: {
            'Content-Type': 'application/json'
          }
        })
      } else {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error'

        return new Response(JSON.stringify({ error: errorMessage }), {
          status: 500,
          statusText: 'Internal Server Error',
          headers: {
            'Content-Type': 'application/json'
          }
        })
      }
    }
  }
