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, department, and team
    const adminData = (await executeQuery(
      "SELECT field, department, team 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, team: adminTeam } = adminData[0]

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

    // Get team stats with full context (field + department + team)
    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 = ? AND team = ?
    `,
      [adminField, adminDepartment, adminTeam],
    )) as any[]

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