import type { APIRoute } from 'astro'

import { resolveInternalApiBaseUrl } from '../../../lib/api/client'
import {
  MAINTENANCE_ACCESS_COOKIE_NAME,
  sanitizeMaintenanceReturnTo,
} from '../../../lib/maintenance'

interface MaintenanceVerifyResponse {
  maintenance_mode_enabled?: boolean
  access_granted?: boolean
  access_token?: string | null
}

export const POST: APIRoute = async ({ request, url, cookies, redirect }) => {
  const contentType = request.headers.get('content-type') ?? ''
  let code = ''
  let returnTo = '/'

  if (contentType.includes('application/json')) {
    const payload = (await request.json().catch(() => ({}))) as {
      code?: unknown
      returnTo?: unknown
    }
    code = String(payload.code ?? '').trim()
    returnTo = sanitizeMaintenanceReturnTo(String(payload.returnTo ?? '/'))
  } else {
    const formData = await request.formData().catch(() => null)
    code = String(formData?.get('code') ?? '').trim()
    returnTo = sanitizeMaintenanceReturnTo(String(formData?.get('returnTo') ?? '/'))
  }

  if (!code) {
    return redirect(`/maintenance?error=empty&returnTo=${encodeURIComponent(returnTo)}`, 302)
  }

  try {
    const response = await fetch(`${resolveInternalApiBaseUrl(url)}/site_settings/maintenance/verify`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ code }),
    })

    if (!response.ok) {
      throw new Error(`Maintenance verify request failed: ${response.status}`)
    }

    const payload = (await response.json()) as MaintenanceVerifyResponse
    const maintenanceModeEnabled = Boolean(payload.maintenance_mode_enabled)
    const accessGranted = Boolean(payload.access_granted)
    const accessToken = payload.access_token?.trim()

    if (!maintenanceModeEnabled) {
      cookies.set(MAINTENANCE_ACCESS_COOKIE_NAME, '', {
        httpOnly: true,
        sameSite: 'lax',
        secure: url.protocol === 'https:',
        path: '/',
        maxAge: 0,
      })

      return redirect(returnTo, 302)
    }

    if (accessGranted && accessToken) {
      cookies.set(MAINTENANCE_ACCESS_COOKIE_NAME, accessToken, {
        httpOnly: true,
        sameSite: 'lax',
        secure: url.protocol === 'https:',
        path: '/',
        maxAge: 60 * 60 * 24 * 7,
      })

      return redirect(returnTo, 302)
    }

    cookies.set(MAINTENANCE_ACCESS_COOKIE_NAME, '', {
      httpOnly: true,
      sameSite: 'lax',
      secure: url.protocol === 'https:',
      path: '/',
      maxAge: 0,
    })

    return redirect(`/maintenance?error=invalid&returnTo=${encodeURIComponent(returnTo)}`, 302)
  } catch (error) {
    console.error('Failed to unlock maintenance mode:', error)
    return redirect(`/maintenance?error=unavailable&returnTo=${encodeURIComponent(returnTo)}`, 302)
  }
}
