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

export async function GET(request: NextRequest) {
    try {
        // Server-side: use the hostname directly (should be in /etc/hosts for MAMP PRO)
        // For local development, prefer HTTP to avoid SSL certificate issues
        let apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8890';
        
        // Extract protocol and port
        const urlMatch = apiUrl.match(/https?:\/\/([^:/]+)(:\d+)?/);
        if (urlMatch) {
            const port = urlMatch[2] || ':8890';
            
            // MAMP PRO requires HTTPS on port 8890
            // Use property-app hostname as it's configured in MAMP PRO
            apiUrl = `https://property-app${port}`;
        } else {
            apiUrl = 'https://property-app:8890';
        }
        
        const cookies = request.headers.get('cookie') || '';
        
        console.log('Dashboard request - cookies received:', cookies ? `${cookies.substring(0, 100)}...` : 'none');
        console.log('Fetching from API URL:', `${apiUrl}/api/dashboard`);
        
        // Forward the request to Laravel API
        // Note: For HTTPS with self-signed certs, NODE_TLS_REJECT_UNAUTHORIZED=0 must be set
        // This is safe for local development with MAMP PRO
        const response = await fetch(`${apiUrl}/api/dashboard`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Cookie': cookies,
                'X-Requested-With': 'XMLHttpRequest',
            },
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error(`Laravel API error (${response.status}):`, errorText);
            return NextResponse.json(
                { error: `API Error: ${response.status} - ${errorText.substring(0, 200)}` },
                { status: response.status }
            );
        }

        const data = await response.json();
        // #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:'api/dashboard/route.ts:33',message:'Dashboard API data received',data:{hasProperties:!!data.properties,propertiesCount:data.properties?.length||0,firstVendorServiceTypes:data.properties?.[0]?.vendors?.[0]?.service_types,firstVendorServiceTypesType:typeof data.properties?.[0]?.vendors?.[0]?.service_types},sessionId:'debug-session',runId:'run1',hypothesisId:'H9'})}).catch(()=>{});
        // #endregion
        
        // Forward any Set-Cookie headers from Laravel to the client
        const responseHeaders = new Headers();
        response.headers.forEach((value, key) => {
            if (key.toLowerCase() === 'set-cookie') {
                responseHeaders.append('Set-Cookie', value);
            }
        });
        
        return NextResponse.json(data, { headers: responseHeaders });
    } catch (error) {
        console.error('API proxy error:', error);
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        const errorStack = error instanceof Error ? error.stack : undefined;
        let apiUrl = process.env.NEXT_PUBLIC_API_URL || 'https://property-app:8890';
        const urlMatch = apiUrl.match(/https?:\/\/([^:/]+)(:\d+)?/);
        if (urlMatch) {
            const port = urlMatch[2] || ':8890';
            const hostname = urlMatch[1];
            // Always use HTTPS for MAMP PRO on port 8890
            apiUrl = `https://${hostname}${port}`;
        } else {
            apiUrl = 'https://property-app:8890';
        }
        console.error('Full error details:', { errorMessage, errorStack, apiUrl });
        
        // Check if it's a certificate/SSL error
        if (errorMessage.includes('certificate') || errorMessage.includes('self-signed') || errorMessage.includes('UNABLE_TO_VERIFY_LEAF_SIGNATURE')) {
            return NextResponse.json(
                { error: 'SSL certificate error. Make sure NODE_TLS_REJECT_UNAUTHORIZED=0 is set and Next.js server is restarted.' },
                { status: 500 }
            );
        }
        
        return NextResponse.json(
            { error: `Failed to fetch dashboard data: ${errorMessage}` },
            { status: 500 }
        );
    }
}

