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

export const runtime = "nodejs";

// GET - fetch single sprint by ID
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const user = await getAuthenticatedUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const { id } = await params;
    
    const supabase = getServiceSupabase();
    const { data, error } = await supabase
      .from("sprints")
      .select("*")
      .eq("id", id)
      .single();
    
    if (error) {
      if (error.code === "PGRST116") {
        return NextResponse.json({ error: "Sprint not found" }, { status: 404 });
      }
      throw error;
    }
    
    const startDate = typeof data.start_date === "string" && data.start_date.trim().length > 0 ? data.start_date : null;
    const endDate = typeof data.end_date === "string" && data.end_date.trim().length > 0 ? data.end_date : null;
    if (!startDate || !endDate) {
      throw new Error("Sprint row is missing start_date or end_date");
    }
    const sprint = {
      ...data,
      status: inferSprintStatusForDateRange(startDate, endDate),
    };

    return NextResponse.json({ sprint });
  } catch (error) {
    console.error(">>> API GET /sprints/[id] error:", error);
    return NextResponse.json({ error: "Failed to fetch sprint" }, { status: 500 });
  }
}
