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

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { id } = await params

    const result = await query(
      `SELECT pm.id, pm.name, pm.description, pm.sort_order, pm.status, pm.start_date, pm.due_date, pm.completed_at, pm.created_at,
              COALESCE(
                json_agg(
                  json_build_object(
                    'id', t.id,
                    'title', t.title,
                    'description', t.description,
                    'status', t.status,
                    'due_date', t.due_date,
                    'completed_at', t.completed_at,
                    'assigned_to', t.assigned_to,
                    'created_at', t.created_at
                  )
                  ORDER BY t.created_at DESC
                ) FILTER (WHERE t.id IS NOT NULL),
                '[]'::json
              ) AS tasks
       FROM project_milestones pm
       LEFT JOIN tasks t ON t.milestone_id = pm.id AND t.deleted_at IS NULL
       WHERE pm.project_id = $1
       GROUP BY pm.id, pm.name, pm.description, pm.sort_order, pm.status, pm.start_date, pm.due_date, pm.completed_at, pm.created_at
       ORDER BY pm.sort_order`,
      [id]
    )

    return NextResponse.json(result.rows)
  } catch (error) {
    console.error("Milestones API error:", error)
    return NextResponse.json({ error: "Failed to load milestones" }, { status: 500 })
  }
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { id } = await params
    const body = await request.json()

    const maxOrder = await query(
      "SELECT COALESCE(MAX(sort_order), 0) + 1 AS next_order FROM project_milestones WHERE project_id = $1",
      [id]
    )

    const result = await query(
      `INSERT INTO project_milestones (project_id, name, description, sort_order, start_date, due_date)
       VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`,
      [id, body.name, body.description || null, maxOrder.rows[0].next_order, body.startDate || null, body.dueDate || null]
    )

    return NextResponse.json({ success: true, id: result.rows[0].id }, { status: 201 })
  } catch (error) {
    console.error("Milestones POST error:", error)
    return NextResponse.json({ error: "Failed to create milestone" }, { status: 500 })
  }
}
