import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getSessionCookieName, verifySessionToken } from '@/lib/session';

const PUBLIC_PATHS = new Set(['/login']);
const PUBLIC_API_PATHS = new Set(['/api/auth/login', '/api/settings/init', '/api/settings/status']);

export default async function proxy(request: NextRequest) {
    const authCookie = request.cookies.get(getSessionCookieName());
    const isLoginPage = request.nextUrl.pathname === '/login';
    const isPublicPath = PUBLIC_PATHS.has(request.nextUrl.pathname);
    const isPublicApiPath = PUBLIC_API_PATHS.has(request.nextUrl.pathname);
    const session = authCookie ? await verifySessionToken(authCookie.value) : null;
    const isAuthenticated = session !== null;

    if (!isAuthenticated && !isPublicPath && !isPublicApiPath) {
        if (request.nextUrl.pathname.startsWith('/api')) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }
        return NextResponse.redirect(new URL('/login', request.url));
    }

    if (isAuthenticated && isLoginPage) {
        return NextResponse.redirect(new URL('/', request.url));
    }

    return NextResponse.next();
}

export const config = {
    matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
