import { NextResponse } from "next/server"
import { getServiceSupabase } from "@/lib/supabase/client"
import { getAuthenticatedUser } from "@/lib/server/auth"
import { findCurrentSprint } from "@/lib/server/sprintSelection"
import { inferSprintStatusForDateRange } from "@/lib/server/sprintState"

export const runtime = "nodejs"

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

    const supabase = getServiceSupabase()
    const { data, error } = await supabase
      .from("sprints")
      .select("id,name,goal,start_date,end_date,created_at")
      .order("start_date", { ascending: true })

    if (error) throw error

    const mapped = (data || []).map((row) => ({
      id: row.id,
      name: row.name,
      goal: row.goal,
      startDate: row.start_date,
      endDate: row.end_date,
      status: inferSprintStatusForDateRange(row.start_date, row.end_date),
      createdAt: row.created_at,
    }))

    const sprint = findCurrentSprint(mapped)
    return NextResponse.json({ sprint })
  } catch (error) {
    console.error(">>> API GET /sprints/current error:", error)
    return NextResponse.json({ error: "Failed to resolve current sprint" }, { status: 500 })
  }
}
