import type { APIRoute } from 'astro'

import { createApiClient, DEFAULT_SITE_SETTINGS } from '../lib/api/client'

function resolveFaviconTarget(requestUrl: URL, configured: string | undefined) {
  const fallbackTarget = '/favicon-default.ico'
  const candidate = configured?.trim()

  if (!candidate) {
    return fallbackTarget
  }

  try {
    const resolved = new URL(candidate, requestUrl)
    if (resolved.pathname === '/favicon.ico' && resolved.origin === requestUrl.origin) {
      return fallbackTarget
    }

    return resolved.toString()
  } catch {
    return fallbackTarget
  }
}

export const GET: APIRoute = async ({ url, redirect }) => {
  let siteSettings = DEFAULT_SITE_SETTINGS

  try {
    siteSettings = await createApiClient({ requestUrl: url }).getSiteSettings()
  } catch (error) {
    console.error('Failed to load site settings for favicon:', error)
  }

  return redirect(resolveFaviconTarget(url, siteSettings.seo.faviconUrl), 302)
}
