import { NextResponse } from 'next/server';

export async function POST(req) {
    try {
        const body = await req.json();
        const backendResponse = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/auth/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });

        if (!backendResponse.ok) {
            const errorData = await backendResponse.json();
            return NextResponse.json(
                { message: errorData.message || 'Authentication failed' },
                { status: backendResponse.status }
            );
        }

        const { token, user } = await backendResponse.json();

        if (!token) {
            throw new Error('No token received from backend');
        }

        const response = NextResponse.json(
            { user },
            { status: 200 }
        );

        // Store token in HttpOnly cookie
        response.cookies.set('token', token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            sameSite: 'lax',
            path: '/',
            maxAge: 60 * 60 * 24, // 1 day
        });

        return response;
    } catch (err) {
        console.error(err);
        return new Response(JSON.stringify({ error: 'Server error' }), { status: 500 });
    }
}
