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

export async function PATCH(request: NextRequest) {
  try {
    const id = request.url.split('/').filter(Boolean).pop();

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'User ID is required' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const { banned, banReason, adminId } = body;

    if (banned === undefined || !adminId) {
      return NextResponse.json(
        { success: false, error: 'Banned status and adminId are required' },
        { status: 400 }
      );
    }

    const existingUser = await db.user.findUnique({
      where: { id },
    });

    if (!existingUser) {
      return NextResponse.json(
        { success: false, error: 'User not found' },
        { status: 404 }
      );
    }

    // Verify admin exists
    const admin = await db.user.findUnique({ where: { id: adminId } });
    if (!admin || admin.role !== 'admin') {
      return NextResponse.json(
        { success: false, error: 'Unauthorized: Admin access required' },
        { status: 401 }
      );
    }

    const updatedUser = await db.user.update({
      where: { id },
      data: {
        banned: Boolean(banned),
        banReason: banned ? (banReason || null) : null,
      },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        banned: true,
        banReason: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    // Create admin log entry
    await db.adminLog.create({
      data: {
        adminId,
        action: banned ? 'ban_user' : 'unban_user',
        targetType: 'user',
        targetId: id,
        details: banned
          ? `User banned. Reason: ${banReason || 'Not specified'}`
          : 'User unbanned',
      },
    });

    return NextResponse.json(
      { success: true, data: updatedUser },
      { status: 200 }
    );
  } catch (error) {
    console.error('Admin ban/unban user error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
