import createMiddleware from 'next-intl/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { routing } from './src/i18n/routing';

// Protected routes that require authentication
const protectedRoutes = [
  '/dashboard',
  '/profile',
  '/messages',
  '/products/create',
];

// Auth routes that should redirect to dashboard if already logged in
const authRoutes = [
  '/auth/login',
  '/auth/forgot-password',
];

function isProtectedRoute(pathname: string): boolean {
  return protectedRoutes.some(route => pathname.includes(route));
}

function isAuthRoute(pathname: string): boolean {
  return authRoutes.some(route => pathname.includes(route));
}

export default function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;

  const host = request.headers.get('host')?.split(':')[0]?.toLowerCase();
  if (host === 'www.vaaim.ch') {
    const url = request.nextUrl.clone();
    url.hostname = 'vaaim.ch';
    return NextResponse.redirect(url, 301);
  }

  // API subdomain must not serve marketing/SEO pages — send crawlers and users to vaaim.ch
  if (host === 'api.vaaim.ch') {
    const isApiRoute =
      pathname.startsWith('/api') ||
      pathname.startsWith('/sanctum') ||
      pathname.startsWith('/storage') ||
      pathname === '/robots.txt';
    if (!isApiRoute) {
      const url = request.nextUrl.clone();
      url.hostname = 'vaaim.ch';
      return NextResponse.redirect(url, 301);
    }
  }

  // SEO paths without locale prefix (legacy / mistaken URLs) → canonical /de/... or /en/...
  const localePrefixMatch = pathname.match(/^\/(en|de)(\/|$)/);
  if (!localePrefixMatch) {
    const seoPathMatch = pathname.match(/^\/(locations|categories|collections|blog|lp)(\/.*)?$/);
    if (seoPathMatch) {
      const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
      const locale = cookieLocale === 'en' ? 'en' : 'de';
      const url = request.nextUrl.clone();
      url.pathname = `/${locale}${pathname}`;
      return NextResponse.redirect(url, 301);
    }
    if (pathname === '/search' || pathname.startsWith('/search/')) {
      const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
      const locale = cookieLocale === 'en' ? 'en' : 'de';
      const url = request.nextUrl.clone();
      url.pathname = `/${locale}${pathname}`;
      return NextResponse.redirect(url, 301);
    }
  }

  // Skip middleware for API routes, static files, and common static file extensions
  const staticFileExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.avif', '.woff', '.woff2', '.ttf', '.eot', '.css', '.js', '.json', '.xml', '.txt', '.pdf', '.zip'];
  const isStaticFile = staticFileExtensions.some(ext => pathname.toLowerCase().endsWith(ext));
  
  if (
    pathname.startsWith('/api') || 
    pathname.startsWith('/_next') || 
    pathname.startsWith('/_vercel') ||
    pathname.includes('.') ||
    isStaticFile ||
    pathname === '/favicon.ico' ||
    pathname === '/robots.txt' ||
    pathname === '/sitemap.xml' ||
    pathname.startsWith('/sitemaps/') ||
    pathname.startsWith('/sw.js') ||
    pathname.startsWith('/manifest.json')
  ) {
    return NextResponse.next();
  }

  // Temporarily disable all auth checks in middleware


  // Check if this is a protected route
  if (isProtectedRoute(pathname)) {


    // Note: Middleware runs on the server and cannot access localStorage
    // We'll disable server-side auth checks and let the client handle it


    // For now, let all requests through and let client-side auth handle it
    // const token = request.cookies.get('token')?.value ||
    //   request.headers.get('authorization')?.replace('Bearer ', '');

    // console.log("Middleware: Token found:", !!token);

    // if (!token) {
    //   console.log("Middleware: No token, redirecting to login");
    //   // Redirect to login page
    //   const loginUrl = new URL('/auth/login', request.url);
    //   return NextResponse.redirect(loginUrl);
    // }
  }

  // Check if user is already logged in and trying to access auth routes
  // Temporarily disabled because tokens are stored in localStorage, not cookies
  // if (isAuthRoute(pathname)) {
  //   const token = request.cookies.get('token')?.value ||
  //     request.headers.get('authorization')?.replace('Bearer ', '');

  //   if (token) {
  //     // Redirect to dashboard
  //     const dashboardUrl = new URL('/dashboard', request.url);
  //     return NextResponse.redirect(dashboardUrl);
  //   }
  // }

  // Apply next-intl middleware with language persistence using the same routing config
  const intlMiddleware = createMiddleware(routing);
  const response = intlMiddleware(request);
  
  // Add security headers (HSTS, etc.)
  if (request.nextUrl.protocol === 'https:') {
    response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
  }
  
  // Add other security headers
  response.headers.set('X-Content-Type-Options', 'nosniff');
  response.headers.set('X-Frame-Options', 'DENY');
  response.headers.set('X-XSS-Protection', '1; mode=block');
  response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
  
  return response;
}

export const config = {
  matcher: [
    // Match all pathnames except for
    // - … if they start with `/api`, `/_next`, `/_vercel`, `/sitemaps`, `/sitemap.xml`, `/robots.txt`
    // - … the ones containing a dot (e.g. `favicon.ico`, `icon-192x192.png`)
    // - … static file extensions and service worker files
    '/((?!api|_next|_vercel|sitemaps|sitemap\\.xml|robots\\.txt|sw\\.js|manifest\\.json|.*\\..*).*)'
  ]
};
