import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { decryptServer } from './utils/ServerCrypto'

// Routes that require authentication
const protectedRoutes = [
    '/',
    '/documents/',
    '/policy-compliance-review/',
    '/settings/profile/'
]

// Routes that should redirect to / if authenticated
const authRoutes = ['/login/', '/register/', '/forgot-password/', '/reset-password/', '/verify-your-email/']

export default function proxy(request: NextRequest) {
    const authStore = request.cookies.get('auth-store')?.value // or 'session', 'access_token', etc.
    const decryptedStore = decryptServer(authStore ?? '')
    // console.log('decryptedStore', JSON.parse(decryptedStore))
    const parsedStore = decryptedStore && JSON.parse(decryptedStore)

    const token = parsedStore?.state?.token || null

    const { pathname } = request.nextUrl


    if (pathname === '/.well-known/appspecific/com.chrome.devtools.json') {
        return NextResponse.next()
    }

    // Check if route is protected
    const isProtectedRoute = protectedRoutes.includes(pathname)
    const isAuthRoute = authRoutes.includes(pathname)

    // If the user is authenticated
    if (token) {
        if (isAuthRoute) {
            // Redirect to the homepage/dashboard if the user is already logged in and trying to visit /login/ or /register/
            const url = request.nextUrl.clone()
            url.pathname = '/'
            console.log(
                'Redirecting to dashboard/home as the user is already authenticated.'
            )
            return NextResponse.redirect(url)
        }
    } else {
        // If the user is not authenticated
        if (isProtectedRoute) {
            // Redirect to login page if the user is trying to access protected routes without being authenticated
            const url = request.nextUrl.clone()
            url.pathname = '/login/'
            console.log(
                'Redirecting to login page as the user is not authenticated.'
            )
            return NextResponse.redirect(url)
        }
    }

    // If no redirects are needed, continue with the request
    return NextResponse.next()
}

export const config = {
    matcher: [
        '/((?!api|_next/static|_next/image|favicon.ico|uploads|\\.well-known/).*)'
    ]
}
