import { type NextRequest, NextResponse } from "next/server"
import { safeQuery } from "@/lib/database"

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

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

    // Get admin's field
    const adminData = (await safeQuery("SELECT field 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 adminField = adminData[0].field

    if (!adminField) {
      return NextResponse.json({ error: "למנהל לא הוגדר תחום" }, { status: 400 })
    }

    // Check cooldown for field resets
    //const lastReset = (await safeQuery(
      //'SELECT timestamp FROM admin_actions WHERE action_type = "reset_field" AND admin_id = ? ORDER BY timestamp DESC LIMIT 1',
     // [adminId],
   // )) as any[]

   // if (lastReset.length > 0) {
  //    const lastResetTime = new Date(lastReset[0].timestamp).getTime()
  //    const now = new Date().getTime()
  //    const cooldownMs = 30 * 10 // 30 seconds for field resets

  //    if (now - lastResetTime < cooldownMs) {
  //      const remainingSeconds = Math.ceil((cooldownMs - (now - lastResetTime)) / 1000)
 //       return NextResponse.json({ error: "יש להמתין 30 שניות בין איפוסי מסגרת", remainingSeconds }, { status: 429 })
 //     }

 //   }

    // Reset field users' statuses, but exclude locked users
    await safeQuery("UPDATE users SET in_shelter = NULL, last_updated = NULL WHERE field = ? AND lock_status = FALSE", [
      adminField,
    ])

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

    console.log(`Department reset was called by: ${adminId}`)

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

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

    return NextResponse.json({ success: true, field: adminField, message, lockedCount })
  } catch (error) {
    console.error("Field reset error:", error)
    return NextResponse.json({ error: "שגיאה באיפוס התחום" }, { status: 500 })
  }
}
