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

const locales = ['fi', 'en', 'sv'];
const defaultLocale = 'fi';

// Get the preferred locale from the request
function getLocale(request: NextRequest): string {
    // Check Accept-Language header
    const acceptLanguage = request.headers.get('accept-language');
    if (acceptLanguage) {
        const preferredLocale = acceptLanguage
            .split(',')
            .map((lang) => lang.split(';')[0].trim())
            .find((lang) => {
                if (lang.startsWith('en')) return 'en';
                if (lang.startsWith('sv')) return 'sv';
                if (lang.startsWith('fi')) return 'fi';
                return null;
            });

        if (preferredLocale) {
            return preferredLocale.startsWith('en') ? 'en' :
                preferredLocale.startsWith('sv') ? 'sv' : 'fi';
        }
    }

    return defaultLocale;
}

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

    // Skip middleware for static files and API routes
    if (
        pathname.startsWith('/_next') ||
        pathname.startsWith('/api') ||
        pathname.includes('.') ||
        pathname.startsWith('/favicon')
    ) {
        return NextResponse.next();
    }

    // Check if this is an existing Finnish route (don't redirect these)
    const existingFinnishRoutes = ['/palvelut', '/palvelut/kirjanpito', '/palvelut/palkanlaskenta', '/palvelut/verotus', '/yhteystiedot', '/tietoa-meista'];
    const isExistingFinnishRoute = existingFinnishRoutes.some(route => pathname.startsWith(route));

    if (isExistingFinnishRoute) {
        return NextResponse.next();
    }

    // Check if there is any supported locale in the pathname
    const pathnameIsMissingLocale = locales.every(
        (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
    );

    // Redirect if there is no locale
    if (pathnameIsMissingLocale) {
        const locale = getLocale(request);

        // Handle root path - serve Finnish homepage directly (no redirect needed)
        if (pathname === '/') {
            return NextResponse.next();
        }

        // Handle other paths - redirect to localized versions
        return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url));
    }

    return NextResponse.next();
}

export const config = {
    matcher: [
        // Skip all internal paths (_next)
        '/((?!_next|api|favicon.ico).*)',
    ],
};
