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

const API = process.env.NEXT_PUBLIC_API_URL ?? 'http://127.0.0.1:3000';

/**
 * FIX-14: admin panel auth now goes through the backoffice auth endpoint,
 * which sets a separate `backoffice_session` cookie (independent of the
 * storefront `mdv_session`). This keeps the physical separation between
 * backoffice users and storefront customers.
 */
function makeLocalhostCompatible(cookie: string): string {
  return cookie
    .replace(/;\s*Secure/gi, '')
    .replace(/;\s*SameSite=Lax/gi, '')
    .trim();
}

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

    const backendRes = await fetch(`${API}/backoffice/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });

    const data = await backendRes.json();

    if (!backendRes.ok) {
      return NextResponse.json(data, { status: backendRes.status });
    }

    const setCookie = backendRes.headers.get('set-cookie');
    const response = NextResponse.json(data, { status: 200 });
    if (setCookie) {
      response.headers.set('Set-Cookie', makeLocalhostCompatible(setCookie));
    }
    return response;
  } catch {
    return NextResponse.json(
      { statusCode: 500, code: 'SERVER_ERROR', message: 'Error del servidor' },
      { status: 500 },
    );
  }
}