import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { updateSession, decrypt } from './lib/auth'

const locales = ['en', 'tr'];
const defaultLocale = 'tr';

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

  // --- Admin Auth Logic ---
  const isAdminPath = pathname.startsWith('/admin');
  if (isAdminPath) {
    // Always update session expiration for admin
    let response = await updateSession(request)

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

    // Check if session exists and is valid
    const sessionValue = request.cookies.get('session')?.value
    let session = null
    if (sessionValue) {
      try {
        session = await decrypt(sessionValue)
      } catch(e) {
        session = null
      }
    }

    // If trying to access admin pages (except login) without a valid session
    if (!isAuthPage && !session) {
      return NextResponse.redirect(new URL('/admin/login', request.url))
    }

    // If trying to access login page with a valid session
    if (isAuthPage && session) {
      return NextResponse.redirect(new URL('/admin', request.url))
    }

    return response || NextResponse.next()
  }

  // --- i18n Logic ---
  const isPublicFile = pathname.includes('.') || pathname.startsWith('/_next') || pathname.startsWith('/api');
  
  if (!isPublicFile) {
    const pathnameHasLocale = locales.some(
      (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
    );

    if (!pathnameHasLocale) {
      // Redirect if there is no locale
      request.nextUrl.pathname = `/${defaultLocale}${pathname}`;
      return NextResponse.redirect(request.nextUrl);
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    // Apply proxy to all paths except public static assets
    '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|avif)$).*)',
  ],
}
