import { NextResponse } from "next/server"
import { executeQuery } from "@/lib/database"

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

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

    // Get admin's field and department
    const adminData = (await executeQuery(
      "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" || !adminField || !adminDepartment) {
      return NextResponse.json({
        no_report: 0,
        in_shelter: 0,
        not_in_shelter: 0,
        no_alarm: 0,
        safe_after_exit: 0,
        field: adminField,
        department: adminDepartment,
      })
    }

    // Get department stats with field and department context
    const results = (await executeQuery(
      `
      SELECT 
        SUM(CASE WHEN in_shelter IS NULL THEN 1 ELSE 0 END) as no_report,
        SUM(CASE WHEN in_shelter = 'yes' THEN 1 ELSE 0 END) as in_shelter,
        SUM(CASE WHEN in_shelter = 'no' THEN 1 ELSE 0 END) as not_in_shelter,
        SUM(CASE WHEN in_shelter = 'no_alarm' THEN 1 ELSE 0 END) as no_alarm,
        SUM(CASE WHEN in_shelter = 'safe_after_exit' THEN 1 ELSE 0 END) as safe_after_exit
      FROM users
      WHERE field = ? AND department = ?
    `,
      [adminField, adminDepartment],
    )) as any[]

    return NextResponse.json({
      ...results[0],
      field: adminField,
      department: adminDepartment,
    })
  } catch (error) {
    console.error("Department stats error:", error)
    return NextResponse.json({ error: "שגיאה בטעינת סטטיסטיקות המסגרת" }, { status: 500 })
  }
}
