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

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

    // Check cooldown
    //const lastReset = (await safeQuery(
      //'SELECT timestamp FROM admin_actions WHERE action_type = "reset_all" ORDER BY timestamp DESC LIMIT 1',
    //)) as any[]

    //if (lastReset.length > 0) {
      //const lastResetTime = new Date(lastReset[0].timestamp).getTime()
      //const now = new Date().getTime()
      //const cooldownMs = 2 * 60 * 10 // 2 minutes in milliseconds

      //const timeSinceReset = now - lastResetTime

      //console.log("Reset cooldown check:", {
        //lastResetTime: new Date(lastResetTime).toISOString(),
        //now: new Date(now).toISOString(),
        //timeSinceReset: timeSinceReset,
        //cooldownMs: cooldownMs,
        //remainingMs: cooldownMs - timeSinceReset,
      //})

      //if (timeSinceReset < cooldownMs) {
        //const remainingSeconds = Math.ceil((cooldownMs - timeSinceReset) / 10)
        //return NextResponse.json(
          //{
            //error: `יש להמתין ${remainingSeconds} שניות בין איפוסים`,
            //remainingSeconds,
            //cooldownMs,
          //},
          //{ status: 429 },
        //)
      //}
    //}

    // Reset ALL users' statuses including admins, but exclude locked users
    const result = await safeQuery("UPDATE users SET in_shelter = NULL, last_updated = NULL WHERE lock_status = FALSE")

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

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

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

    console.log("Reset completed:", {
      affectedRows: (result as any).affectedRows,
      lockedCount,
      adminId,
    })

    return NextResponse.json({
      success: true,
      message,
      lockedCount,
      affectedRows: (result as any).affectedRows,
    })
  } catch (error) {
    console.error("Reset error:", error)
    return NextResponse.json({ error: "שגיאה באיפוס" }, { status: 500 })
  }
}
