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 isDashboardRoute =
    pathname === '/dashboard' || pathname.startsWith('/dashboard/');

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


  /**
   * DASHBOARD PROTECTION
   */
  if (isDashboardRoute && (!clienttoken || clientExpired)) {
    const loginUrl = request.nextUrl.clone();
    loginUrl.pathname = '/login';
    loginUrl.searchParams.set('next', pathname);
    return NextResponse.redirect(loginUrl);
  }

  /**
   * 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) {
    const redirectUrl = request.nextUrl.clone();
    const nextPage = request.nextUrl.searchParams.get('next');
    redirectUrl.pathname =
      nextPage && nextPage.startsWith('/') ? nextPage : '/dashboard';
    redirectUrl.search = '';
    return NextResponse.redirect(redirectUrl);
  }

  const response = NextResponse.next();

  response.headers.set("url-pathname", pathname);

  return response;
}

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