import createMiddleware from 'next-intl/middleware';
import { routing } from './i18n/routing';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';

const intlMiddleware = createMiddleware(routing);

export async function middleware(request: NextRequest) {
  // Execute internationalization middleware first
  const response = intlMiddleware(request);

  // Pathname before rewrite (e.g., /id/admin/dashboard, /admin/dashboard)
  const pathname = request.nextUrl.pathname;
  
  // Protect all /admin routes except the login page
  const isAdminRoute = pathname.includes('/admin') && !pathname.includes('/admin/login');

  if (isAdminRoute) {
    const session = request.cookies.get('ando_admin_session')?.value;
    
    // Determine current locale from path or cookie for redirect
    const segments = pathname.split('/');
    const localeIndex = routing.locales.includes(segments[1] as any) ? 1 : -1;
    const locale = localeIndex !== -1 ? segments[localeIndex] : routing.defaultLocale;

    if (!session) {
      return NextResponse.redirect(new URL(`/${locale}/admin/login`, request.url));
    }

    try {
      const secretKey = process.env.JWT_SECRET || "fallback-secret-for-development";
      const key = new TextEncoder().encode(secretKey);
      await jwtVerify(session, key, { algorithms: ["HS256"] });
    } catch (err) {
      // Token is expired or invalid
      const res = NextResponse.redirect(new URL(`/${locale}/admin/login`, request.url));
      res.cookies.delete('ando_admin_session');
      return res;
    }
  }

  return response;
}

export const config = {
  // Apply middleware to all standard routes and admin routes
  matcher: [
    '/',
    '/(id|en)/:path*',
    '/admin/:path*'
  ]
};
