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


function base64UrlDecode(value: string) {
  let base64 = value.replace(/-/g, '+').replace(/_/g, '/');
  while (base64.length % 4 !== 0) {
    base64 += '=';
  }
  try {
    return atob(base64);
  } catch {
    return '';
  }
}

function parseJwt(token: string) {
  const parts = token.split('.');
  if (parts.length < 2) return null;
  try {
    return JSON.parse(base64UrlDecode(parts[1]));
  } catch {
    return null;
  }
}

function isTokenExpired(token: string) {
  const payload = parseJwt(token);
  if (!payload || typeof payload.exp !== 'number') return true;
  return Math.floor(Date.now() / 1000) >= payload.exp;
}

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const token = request.cookies.get('token')?.value;
  // const { clienttoken } = useAuthContext();
  const clienttoken = request.cookies.get('clienttoken')?.value;
   

  const expired = token ? isTokenExpired(token) : true;
    const clientExpired = clienttoken ? isTokenExpired(clienttoken) : true;

  const isAdminRoute = pathname.startsWith('/admin');
  const isLoginPage = pathname === '/admin/login';

  const isAuthPages =
  pathname === "/login" ||
  pathname === "/register";

  const isCustomerRoute =
    pathname.startsWith('/profile') ||
    pathname.startsWith('/orders') ||
    pathname.startsWith('/cart') ||
    pathname.startsWith('/products');


  /**
   * CUSTOMER PROTECTION
   */
  if (isCustomerRoute && (!clienttoken || clientExpired)) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  /**
   * ADMIN
   */
  if (isAdminRoute && !isLoginPage && (!token || expired)) {
    const response = NextResponse.redirect(new URL('/admin/login', request.url));
    // response.cookies.set('token', '', { path: '/', expires: new Date(0) });
    return response;
  }

  if (isLoginPage && token && !expired) {
    return NextResponse.redirect(new URL('/admin/', request.url));
  }


  /**
   * AUTH PAGES BLOCK IF LOGGED IN
   */
if (isAuthPages && clienttoken && !clientExpired) {
  return NextResponse.redirect(new URL('/dashboard', request.url));
}

  return NextResponse.next();
}

export const config = {
  matcher: [
    '/admin/:path*',
    '/profile/:path*',
    '/orders/:path*',
    '/wishlist/:path*',
     '/login',
    '/register',
  ],
};
