import { type NextRequest, NextResponse } from "next/server"
import { safeQuery } from "@/lib/database"
import { revalidatePath } from 'next/cache' // Crucial for Next.js App Router caching

export async function POST(request: NextRequest) {
  try {
    const { adminId } = await request.json()

    if (!adminId) {
      return NextResponse.json({ error: "מזהה מנהל חסר" }, { status: 400 })
    }

    // Get admin's field, department, and team
    const adminData = (await safeQuery(
      "SELECT role, field, department, team FROM users WHERE national_id = ? AND role IS NOT NULL AND role != 'user'",
      [adminId],
    )) as any[]

    if (adminData.length === 0) {
      return NextResponse.json({ error: "מנהל לא נמצא" }, { status: 404 })
    }

    const { role: adminRole, field: adminField, department: adminDepartment, team: adminTeam } = adminData[0]

    if (adminRole !== "team_admin" && adminRole !== "global_admin") {
      return NextResponse.json({ error: "Insufficient permissions." }, { status: 403 })
    }

    if (!adminField || !adminDepartment || !adminTeam) {
      return NextResponse.json({ error: "Team is not assigned." }, { status: 400 })
    }

    await safeQuery(
      "UPDATE users SET in_shelter = NULL, last_updated = NULL WHERE field = ? AND department = ? AND team = ? AND lock_status = FALSE",
      [adminField, adminDepartment, adminTeam],
    )

    // Get count of locked users that were skipped
    const lockedUsers = (await safeQuery(
      "SELECT COUNT(*) as count FROM users WHERE field = ? AND department = ? AND team = ? AND lock_status = TRUE",
      [adminField, adminDepartment, adminTeam],
    )) as any[]
    const lockedCount = lockedUsers[0]?.count || 0

    // Log the action
    await safeQuery(
      'INSERT INTO admin_actions (admin_id, action_type, target_user_id) VALUES (?, "reset_team", NULL)',
      [adminId],
    )

    revalidatePath('/admin')

    let message = `כל הסטטוסים של צוות ${adminTeam} במסגרת ${adminDepartment} בתחום ${adminField} אופסו בהצלחה`
    if (lockedCount > 0) {
      message += ` (${lockedCount} משתמשים נעולים לא אופסו)`
    }

    return NextResponse.json({
      success: true,
      field: adminField,
      department: adminDepartment,
      team: adminTeam,
      message,
      lockedCount,
    }, { status: 200 })
  } catch (error) {
    console.error("Team reset error:", error)
    return NextResponse.json({ error: "שגיאה באיפוס הצוות" }, { status: 500 })
  }
}