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

export const runtime = "nodejs"

const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

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

    const { id } = (await request.json()) as { id?: string }
    if (!id || !UUID_PATTERN.test(id)) {
      return NextResponse.json({ error: "id must be a valid sprint UUID" }, { status: 400 })
    }

    const supabase = getServiceSupabase()
    const closedEndDate = toLocalDateOnly(addDays(new Date(), -1))
    const { data, error } = await supabase
      .from("sprints")
      .update({ end_date: closedEndDate })
      .eq("id", id)
      .select("*")
      .single()

    if (error) 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")
    }
    return NextResponse.json({
      success: true,
      sprint: {
        ...data,
        status: inferSprintStatusForDateRange(startDate, endDate),
      },
    })
  } catch (error) {
    console.error(">>> API POST /sprints/close error:", error)
    return NextResponse.json({ error: "Failed to close sprint" }, { status: 500 })
  }
}
