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

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();

    // Forward request to FastAPI login endpoint
    const res = await fetch(`${process.env.API_URL}/api/v1/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });

    if (!res.ok) {
      const error = await res.json();
      return NextResponse.json({ error: error.detail }, { status: res.status });
    }

    const data = await res.json();

    // Create a response to send back to the client
    const response = NextResponse.json(data);

    // Set tokens as HTTP-only cookies
    response.cookies.set('access_token', data.access_token, {
      httpOnly: true,
      sameSite: 'strict',
      maxAge: 60 * 60, // 1 hour
      path: '/',
    });

    response.cookies.set('session_token', data.session_token, {
      httpOnly: true,
      sameSite: 'strict',
      maxAge: 12 * 60 * 60, // 12 hours
      path: '/',
    });

    return response;
  } catch (error) {
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
