/*
    This middleware is used to manage all pages routes regarding conditions
*/
import { NextResponse, NextRequest } from 'next/server'

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

    if (url.pathname.startsWith('/home/blog/')) {
        // Set referrer to home page if the pathname starts with /home/blog/
        url.searchParams.set('referrer', 'home');
        return NextResponse.rewrite(url);
    }

    if (url.pathname.startsWith('/home/find-a-home/')) {
        // Set referrer to home page if the pathname starts with /home/find-a-home/
        url.searchParams.set('referrer', 'home');
        return NextResponse.rewrite(url);
    }

    // Check if this is the forgot-password page with an email query param
    if (url.pathname.match(/\/find-a-home\/[^/]+\/book\/profile\/forgot-password\/verification-code\//) && url.searchParams.has('email')) {
        // Extract the email
        const email = url.searchParams.get('email');

        // Remove the query parameter from URL
        url.searchParams.delete('email');

        // Set the email as a cookie
        const response = NextResponse.redirect(url);
        response.cookies.set('forgot-password-email', email, {
            path: '/',
            maxAge: 60 * 10, // 10 minutes expiry
            httpOnly: true, // Makes it accessible only to the server
            sameSite: 'strict'
        });

        return response;
    }

    return NextResponse.next()
}

// This middleware will be applied to all routes
export const config = {
    matcher: '/:path*',
}