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

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    const authHeader = req.headers.get('authorization') || req.headers.get('Authorization')
    const bearer = authHeader && authHeader.toLowerCase().startsWith('bearer ') ? authHeader.slice(7) : undefined
    const secret = process.env.NEXTAUTH_SECRET
    const token = await getToken({ req, secret }).catch(() => null)

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

    if (!accessToken && refreshToken) {
      try {
        const refreshRes = await fetch(`${process.env.BACKEND_URL}/auth/refresh/`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ refresh: refreshToken }),
        })
        if (refreshRes.ok) {
          const refreshed = await refreshRes.json()
          accessToken = refreshed.access
        }
      } catch {}
    }

    if (!accessToken) {
      return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
    }

    const backendUrl = process.env.BACKEND_URL
    if (!backendUrl) {
      return NextResponse.json({ success: false, error: 'BACKEND_URL is not configured' }, { status: 500 })
    }

    const url = new URL(req.url)
    const timePeriod = url.searchParams.get('time_period')
    const qs = timePeriod ? `?time_period=${encodeURIComponent(timePeriod)}` : ''

    const res = await fetch(`${backendUrl}/account/get-dashboard/${qs}`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
      cache: 'no-store',
    })

    const text = await res.text()
    let payload: any
    try { payload = JSON.parse(text) } catch { payload = text }

    if (!res.ok) {
      const err = typeof payload === 'string' ? payload : JSON.stringify(payload)
      return NextResponse.json({ success: false, error: `Backend dashboard error: ${err}` }, { status: res.status })
    }

    return NextResponse.json({ success: true, data: payload })
  } catch (error) {
    console.error('Error fetching dashboard data:', error)
    return NextResponse.json(
      {
        success: false,
        error: 'Failed to fetch dashboard data',
      },
      { status: 500 }
    )
  }
}