import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { updateSession, decrypt } from './lib/auth'
import createIntlMiddleware from 'next-intl/middleware';
import {routing} from './i18n/routing';

const handleI18nRouting = createIntlMiddleware(routing);

export default async function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 1) Handle Admin Routes (Authentication)
  if (pathname.startsWith('/admin')) {
    let response = await updateSession(request)

    const isAuthPage = pathname.startsWith('/admin/login')
    const isAdminPage = pathname.startsWith('/admin')

    const sessionValue = request.cookies.get('session')?.value
    let session = null
    if (sessionValue) {
      try {
        session = await decrypt(sessionValue)
      } catch(e) {
        session = null
      }
    }

    if (isAdminPage && !isAuthPage && !session) {
      return NextResponse.redirect(new URL('/admin/login', request.url))
    }

    if (isAuthPage && session) {
      return NextResponse.redirect(new URL('/admin', request.url))
    }

    return response || NextResponse.next()
  }

  // 2) Skip API and Static Files
  const isInternalOrApi = pathname.startsWith('/api') || 
                          pathname.startsWith('/_next') || 
                          pathname.startsWith('/_vercel') || 
                          pathname.includes('.');
  if (isInternalOrApi) {
    return NextResponse.next();
  }

  // 3) Handle i18n Routing for the public menu
  return handleI18nRouting(request);
}

export const config = {
  // Match everything except internal and api routes
  matcher: ['/((?!api|_next|_vercel|.*\\..*).*)'],
}
