import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// Helper function to decode JWT without verification (for expiration check only)
function decodeJWT(token: string): { exp?: number; [key: string]: any } | null {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) {
      return null;
    }
    
    // Decode the payload (second part)
    const payload = parts[1];
    // Add padding if needed for base64 decoding
    const paddedPayload = payload + '='.repeat((4 - (payload.length % 4)) % 4);
    const decoded = Buffer.from(paddedPayload, 'base64').toString('utf-8');
    
    return JSON.parse(decoded);
  } catch (error) {
    return null;
  }
}

// Helper function to check if token is expired
function isTokenExpired(token: string): boolean {
  const decoded = decodeJWT(token);
  
  if (!decoded || !decoded.exp) {
    return true; // Consider invalid tokens as expired
  }
  
  // exp is in seconds, Date.now() is in milliseconds
  const currentTime = Math.floor(Date.now() / 1000);
  return decoded.exp < currentTime;
}

export function proxy(request: NextRequest) {
  const token = request.cookies.get('__token__');
  const loginUrl = process.env.NEXT_PUBLIC_LOGIN_URL || 'https://rumapedia.in/login';
  const loginUrlWithReturn = `${loginUrl}?redirect=${process.env.NEXT_PUBLIC_APP_URL}`;
  // Get the current path
  const path = request.nextUrl.pathname;
  
  // Allow access to login page, API routes, and static files
  if (
    path.startsWith('/api') ||
    path.startsWith('/_next') ||
    path.startsWith('/login') ||
    path.startsWith('/favicon.ico') ||
    path.startsWith('/images') ||
    path.startsWith('/static')
  ) {
    return NextResponse.next();
  }
  
  // If no token exists, redirect to login


  if (!token) {
    return NextResponse.redirect(new URL(loginUrlWithReturn));
  }
  
  // Check if token is expired
  const tokenValue = token.value;
  if (isTokenExpired(tokenValue)) {
    // Clear the expired token cookie
    const response = NextResponse.redirect(new URL(loginUrlWithReturn));
    response.cookies.delete('__token__');
    return response;
  }
  
  return NextResponse.next();
}

// Configure which routes the middleware should run on
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico|images|static).*)',
  ],
};
