import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { NextRequest } from 'next/server'
import { getToken } from 'next-auth/jwt'

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    const secret = process.env.NEXTAUTH_SECRET
    const token = await getToken({ req, secret }).catch(() => null)

    const accessToken = (session as any)?.accessToken || (token as any)?.accessToken
    const refreshToken = (session as any)?.refreshToken || (token as any)?.refreshToken

    const backendUrl = process.env.BACKEND_URL
    if (!backendUrl) {
      return new Response(JSON.stringify({ success: false, error: 'BACKEND_URL is not configured' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      })
    }

    if (!refreshToken && !accessToken) {
      return new Response(JSON.stringify({ success: false, error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' },
      })
    }

    const payload = refreshToken ? { refresh: refreshToken } : {}
    const headers: Record<string, string> = { 'Content-Type': 'application/json' }
    if (accessToken) headers['Authorization'] = `Bearer ${accessToken}`

    const res = await fetch(`${backendUrl}/auth/logout/`, {
      method: 'POST',
      headers,
      body: JSON.stringify(payload),
    })

    const text = await res.text().catch(() => '')
    const contentType = res.headers.get('Content-Type') || 'application/json'
    return new Response(text || JSON.stringify({ success: res.ok }), {
      status: res.status,
      headers: { 'Content-Type': contentType },
    })
  } catch (error) {
    console.error('Error in logout route:', error)
    return new Response(JSON.stringify({ success: false, error: 'Failed to logout' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    })
  }
}