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

const API_BASE =
  process.env.NEXT_PUBLIC_API_URL_INTERNAL ?? 'http://recipe-api:8080';

async function getAdminSession() {
  const session = await auth();
  if (!session || (session.user as any)?.role !== 'admin') return null;
  return session;
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
  const session = await getAdminSession();
  if (!session) return NextResponse.json({ message: 'Förbjuden' }, { status: 403 });

  const body = await request.json();

  // Om body innehåller isPremium → anropa /premium-endpoint
  if ('isPremium' in body) {
    const res = await fetch(`${API_BASE}/api/users/${id}/premium`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${session.accessToken}`,
      },
      body: JSON.stringify({ isPremium: body.isPremium }),
    });
    const data = await res.json();
    return NextResponse.json(data, { status: res.status });
  }

  // Annars → roll-byte
  const res = await fetch(`${API_BASE}/api/users/${id}/role`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${session.accessToken}`,
    },
    body: JSON.stringify(body),
  });
  const data = await res.json();
  return NextResponse.json(data, { status: res.status });
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
  const session = await getAdminSession();
  if (!session) return NextResponse.json({ message: 'Förbjuden' }, { status: 403 });

  const res = await fetch(`${API_BASE}/api/users/${id}`, {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${session.accessToken}` },
  });
  const data = await res.json().catch(() => ({ deleted: true }));
  return NextResponse.json(data, { status: res.status });
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  // PUT används för e-postbyte (PATCH /api/users/:id/email)
  const { id } = await params;
  const session = await getAdminSession();
  if (!session) return NextResponse.json({ message: 'Förbjuden' }, { status: 403 });

  const body = await request.json();
  const res = await fetch(`${API_BASE}/api/users/${id}/email`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${session.accessToken}`,
    },
    body: JSON.stringify(body),
  });
  const data = await res.json();
  return NextResponse.json(data, { status: res.status });
}

