import { NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"

export async function GET() {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const isAdmin = user.role === "admin" || user.role === "super_admin"
    const userFilter = isAdmin ? "" : "WHERE te.user_id = $1"
    const params = isAdmin ? [] : [user.id]

    const [totals, perProject, perUser] = await Promise.all([
      query(
        `SELECT COALESCE(SUM(duration_minutes), 0) AS total_minutes,
                COALESCE(SUM(CASE WHEN billable THEN duration_minutes ELSE 0 END), 0) AS billable_minutes,
                COALESCE(SUM(duration_minutes * hourly_rate / 60), 0) AS total_revenue,
                COUNT(*) AS entry_count
         FROM time_entries te ${userFilter}`,
        params
      ),
      query(
        `SELECT p.id, p.name,
                COALESCE(SUM(te.duration_minutes), 0) AS total_minutes,
                COALESCE(SUM(CASE WHEN te.billable THEN te.duration_minutes ELSE 0 END), 0) AS billable_minutes,
                COALESCE(SUM(te.duration_minutes * te.hourly_rate / 60), 0) AS revenue
         FROM time_entries te
         LEFT JOIN projects p ON p.id = te.project_id
         ${userFilter ? userFilter + " AND " : "WHERE "} te.project_id IS NOT NULL
         GROUP BY p.id, p.name
         ORDER BY total_minutes DESC
         LIMIT 10`,
        params
      ),
      isAdmin
        ? query(
            `SELECT u.id, u.first_name || ' ' || u.last_name AS name,
                    COALESCE(SUM(te.duration_minutes), 0) AS total_minutes,
                    COALESCE(SUM(te.duration_minutes * te.hourly_rate / 60), 0) AS revenue
             FROM time_entries te
             JOIN users u ON u.id = te.user_id
             GROUP BY u.id, u.first_name, u.last_name
             ORDER BY total_minutes DESC`
          )
        : Promise.resolve({ rows: [] }),
    ])

    return NextResponse.json({
      totals: totals.rows[0],
      perProject: perProject.rows,
      perUser: perUser.rows,
    })
  } catch (error) {
    console.error("Time summary API error:", error)
    return NextResponse.json({ error: "Failed to load summary" }, { status: 500 })
  }
}
