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

export async function POST(request: NextRequest) {
    // #region agent log
    fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'logout/route.ts:3',message:'Logout POST entry',data:{timestamp:Date.now()},sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
    // #endregion
    try {
        // Server-side: use localhost instead of virtual hostname (property-app)
        // Node.js can't resolve MAMP virtual hosts, so we need to use localhost
        let apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8890';
        // Replace virtual hostname with localhost for server-side requests, preserving port
        apiUrl = apiUrl.replace(/https?:\/\/([^:/]+)(:\d+)?/, (match, hostname, port) => {
            const protocol = match.startsWith('https') ? 'https' : 'http';
            return port ? `${protocol}://localhost${port}` : `${protocol}://localhost`;
        });
        const cookies = request.headers.get('cookie') || '';
        // #region agent log
        fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'logout/route.ts:7',message:'Logout cookies check',data:{cookieLength:cookies.length,hasCookies:!!cookies},sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
        // #endregion
        
        // Extract XSRF token from cookies
        let xsrfToken = '';
        if (cookies) {
            const cookieMap = new Map<string, string>();
            cookies.split(';').forEach(cookie => {
                const [name, value] = cookie.trim().split('=');
                if (name && value) {
                    cookieMap.set(name.trim(), value.trim());
                    if (name.trim() === 'XSRF-TOKEN') {
                        try {
                            xsrfToken = decodeURIComponent(value.trim());
                        } catch (error) {
                            xsrfToken = value.trim();
                        }
                    }
                }
            });
        }
        
        // Build headers with XSRF token
        const headers: Record<string, string> = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
        };
        
        if (cookies) {
            headers['Cookie'] = cookies;
        }
        
        if (xsrfToken) {
            headers['X-XSRF-TOKEN'] = xsrfToken;
        }
        // #region agent log
        fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'logout/route.ts:35',message:'Logout request headers',data:{hasCookies:!!headers.Cookie,hasXsrf:!!headers['X-XSRF-TOKEN']},sessionId:'debug-session',runId:'run1',hypothesisId:'H5'})}).catch(()=>{});
        // #endregion
        
        console.log('[DEBUG] Logout request:', { apiUrl: `${apiUrl}/logout`, hasCookies: !!headers.Cookie, hasXsrf: !!headers['X-XSRF-TOKEN'] });
        const response = await fetch(`${apiUrl}/logout`, {
            method: 'POST',
            headers,
        });
        console.log('[DEBUG] Logout response:', { status: response.status, ok: response.ok, statusText: response.statusText });
        // #region agent log
        fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'logout/route.ts:15',message:'Logout response received',data:{status:response.status,ok:response.ok,hasSetCookie:response.headers.get('set-cookie')!==null},sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
        // #endregion

        // Forward Set-Cookie headers (for logout cookie clearing)
        // Modify cookies to work with Next.js proxy on localhost
        const responseHeaders = new Headers();
        let logoutCookieCount = 0;
        response.headers.forEach((value, key) => {
            if (key.toLowerCase() === 'set-cookie') {
                let cookieValue = value;
                
                // Remove domain restriction to allow cookie on localhost
                cookieValue = cookieValue.replace(/;\s*[Dd]omain=[^;]*/gi, '');
                
                // Ensure path is set to root
                if (!cookieValue.match(/;\s*[Pp]ath=/i)) {
                    cookieValue += '; Path=/';
                }
                
                responseHeaders.append('Set-Cookie', cookieValue);
                logoutCookieCount++;
            }
        });
        // #region agent log
        fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'logout/route.ts:25',message:'Logout cookies forwarded',data:{logoutCookieCount},sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
        // #endregion
        
        return NextResponse.json({ success: true }, { 
            status: response.status,
            headers: responseHeaders,
        });
    } catch (error) {
        console.error('Logout proxy error:', error);
        return NextResponse.json(
            { error: 'Logout request failed' },
            { status: 500 }
        );
    }
}

