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 and department
    const adminData = (await safeQuery(
      "SELECT role, field, department 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 } = adminData[0]

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

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

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

    //if (lastReset.length > 0) {
      //const cooldownMs = 30 * 10 // 30 seconds
      //const lastResetTime = new Date(lastReset[0].timestamp).getTime()
      //const now = new Date().getTime()
      //const timeSinceReset = now - lastResetTime
      //console.log("Department 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) / 1000)
        //return NextResponse.json(
          //{
            //error: `יש להמתין ${remainingSeconds} שניות בין איפוסי מסגרת`,
            //remainingSeconds,
            //cooldownMs,
          //},
          //{ status: 429 },
        //)
      //}

    //}

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

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

    // Get count of locked users that were skipped
    const lockedUsers = (await safeQuery(
      "SELECT COUNT(*) as count FROM users WHERE field = ? AND department = ? AND lock_status = TRUE",
      [adminField, adminDepartment],
    )) 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_department", NULL)',
      [adminId],
    )

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

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