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 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 { field: adminField, department: adminDepartment } = adminData[0] if (!adminField || !adminDepartment) { return NextResponse.json({ error: "למנהל לא הוגדרו תחום ומסגרת" }, { 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 lastResetTime = new Date(lastReset[0].timestamp).getTime() const now = new Date().getTime() const cooldownMs = 30 * 10 // 1.5 minutes for department resets if (now - lastResetTime < cooldownMs) { return NextResponse.json({ error: "יש להמתין 30 שניות בין איפוסי מסגרת" }, { 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 }) } }