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

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

/**
 * Catch-all proxy: forwards ALL requests to the backend API.
 * This avoids CORS preflight issues since requests stay within the
 * same origin (localhost:3004 -> localhost:3004 proxy -> 127.0.0.1:3000 backend).
 *
 * More specific routes (e.g. /api/auth/login) take precedence in Next.js,
 * so they are NOT served by this handler.
 */
export async function GET(req: NextRequest) {
  const path = req.nextUrl.pathname.replace('/api/', '');
  const cookies = req.headers.get('cookie') ?? '';
  try {
    const backendRes = await fetch(`${API}/${path}`, {
      headers: { Cookie: cookies },
    });
    if (path === 'admin/logs/stream') {
      return new Response(backendRes.body, {
        status: backendRes.status,
        headers: {
          'Content-Type': backendRes.headers.get('content-type') ?? 'text/event-stream',
          'Cache-Control': backendRes.headers.get('cache-control') ?? 'no-cache',
          Connection: 'keep-alive',
        },
      });
    }
    const data = await backendRes.json().catch(() => null);
    const resp = NextResponse.json(data ?? { error: 'Bad response' }, { status: backendRes.status });
    return resp;
  } catch {
    return NextResponse.json({ error: 'Proxy error' }, { status: 502 });
  }
}

export async function POST(req: NextRequest) {
  const path = req.nextUrl.pathname.replace('/api/', '');
  const cookies = req.headers.get('cookie') ?? '';
  const body = await req.text();
  try {
    const headers: Record<string, string> = { Cookie: cookies };
    if (body) headers['Content-Type'] = 'application/json';
    const backendRes = await fetch(`${API}/${path}`, {
      method: 'POST',
      headers,
      ...(body ? { body } : {}),
    });
    const setCookie = backendRes.headers.get('set-cookie');
    const data = await backendRes.json().catch(() => null);
    const resp = NextResponse.json(data ?? { error: 'Bad response' }, { status: backendRes.status });
    if (setCookie) {
      resp.headers.set(
        'Set-Cookie',
        setCookie.replace(/;\s*Secure/gi, '').replace(/;\s*SameSite=Lax/gi, '').trim(),
      );
    }
    return resp;
  } catch {
    return NextResponse.json({ error: 'Proxy error' }, { status: 502 });
  }
}

export async function PATCH(req: NextRequest) {
  const path = req.nextUrl.pathname.replace('/api/', '');
  const cookies = req.headers.get('cookie') ?? '';
  const body = await req.text();
  try {
    const backendRes = await fetch(`${API}/${path}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json', Cookie: cookies },
      body,
    });
    const data = await backendRes.json().catch(() => null);
    return NextResponse.json(data ?? { error: 'Bad response' }, { status: backendRes.status });
  } catch {
    return NextResponse.json({ error: 'Proxy error' }, { status: 502 });
  }
}

export async function PUT(req: NextRequest) {
  const path = req.nextUrl.pathname.replace('/api/', '');
  const cookies = req.headers.get('cookie') ?? '';
  const body = await req.text();
  try {
    const backendRes = await fetch(`${API}/${path}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', Cookie: cookies },
      body,
    });
    const data = await backendRes.json().catch(() => null);
    return NextResponse.json(data ?? { error: 'Bad response' }, { status: backendRes.status });
  } catch {
    return NextResponse.json({ error: 'Proxy error' }, { status: 502 });
  }
}

export async function DELETE(req: NextRequest) {
  const path = req.nextUrl.pathname.replace('/api/', '');
  const cookies = req.headers.get('cookie') ?? '';
  try {
    const backendRes = await fetch(`${API}/${path}`, {
      method: 'DELETE',
      headers: { Cookie: cookies },
    });
    return NextResponse.json({ ok: backendRes.ok }, { status: backendRes.status });
  } catch {
    return NextResponse.json({ error: 'Proxy error' }, { status: 502 });
  }
}
