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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { action, userIds } = body

    if (!action || !Array.isArray(userIds) || userIds.length === 0) {
      return NextResponse.json(
        { success: false, error: 'Action and userIds are required' },
        { status: 400 }
      )
    }

    if (!['activate', 'suspend', 'delete'].includes(action)) {
      return NextResponse.json(
        { success: false, error: 'Invalid action. Must be activate, suspend, or delete' },
        { status: 400 }
      )
    }

    let result

    switch (action) {
      case 'activate':
        result = await db.user.updateMany({
          where: { id: { in: userIds } },
          data: { status: 'ACTIVE' },
        })
        break
      case 'suspend':
        result = await db.user.updateMany({
          where: { id: { in: userIds } },
          data: { status: 'SUSPENDED' },
        })
        break
      case 'delete':
        await db.user.deleteMany({
          where: { id: { in: userIds } },
        })
        result = { count: userIds.length }
        break
    }

    return NextResponse.json({
      success: true,
      data: {
        action,
        affectedCount: result?.count ?? 0,
      },
      message: `Successfully ${action}d ${result?.count ?? 0} users`,
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
