/**
 * Admin User Ban/Unban API
 */

import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { AuthMiddleware } from '@/lib/auth';

const prisma = new PrismaClient();

/**
 * POST /api/admin/users/[id]/ban
 * Ban a user with optional reason
 *
 * Body: { reason?: string }
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResponse = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResponse) return authResponse;

    const { id } = await params;
    const body = await request.json().catch(() => ({}));
    const { reason } = body;

    // Check user exists
    const existing = await prisma.user.findUnique({ where: { id } });
    if (!existing) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    // Prevent banning admins
    if (existing.role === 'ADMIN') {
      return NextResponse.json({ error: 'Cannot ban admin users' }, { status: 400 });
    }

    // Already banned
    if (existing.isBanned) {
      return NextResponse.json({ error: 'User is already banned' }, { status: 400 });
    }

    const user = await prisma.user.update({
      where: { id },
      data: {
        isBanned: true,
        bannedAt: new Date(),
        bannedReason: reason || 'No reason provided',
        isActive: false, // Also deactivate
      },
      select: {
        id: true,
        email: true,
        isBanned: true,
        bannedAt: true,
        bannedReason: true,
      }
    });

    return NextResponse.json({
      success: true,
      message: `User ${user.email} has been banned`,
      user
    });
  } catch (error: any) {
    console.error('[AdminUserBanAPI] Ban error:', error);
    return NextResponse.json({ error: error.message || 'Internal error' }, { status: 500 });
  }
}

/**
 * DELETE /api/admin/users/[id]/ban
 * Unban a user
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResponse = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResponse) return authResponse;

    const { id } = await params;

    // Check user exists
    const existing = await prisma.user.findUnique({ where: { id } });
    if (!existing) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    // Not banned
    if (!existing.isBanned) {
      return NextResponse.json({ error: 'User is not banned' }, { status: 400 });
    }

    const user = await prisma.user.update({
      where: { id },
      data: {
        isBanned: false,
        bannedAt: null,
        bannedReason: null,
        isActive: true, // Reactivate
      },
      select: {
        id: true,
        email: true,
        isBanned: true,
        isActive: true,
      }
    });

    return NextResponse.json({
      success: true,
      message: `User ${user.email} has been unbanned`,
      user
    });
  } catch (error: any) {
    console.error('[AdminUserBanAPI] Unban error:', error);
    return NextResponse.json({ error: error.message || 'Internal error' }, { status: 500 });
  }
}
