import { NextResponse } from "next/server"
import { query } from "@/lib/db"
import { getPortalSession, isPortalError } from "../../portal-utils"

export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getPortalSession()
  if (isPortalError(session)) return session
  const { id } = await params

  if (!session.customerId) {
    return NextResponse.json({ error: "No customer linked" }, { status: 404 })
  }

  const project = await query(
    `SELECT id, name, description, status, start_date, end_date, budget, currency,
            created_at, updated_at
     FROM projects
     WHERE id = $1 AND customer_id = $2 AND deleted_at IS NULL`,
    [id, session.customerId],
  )

  if (!project.rows[0]) {
    return NextResponse.json({ error: "Project not found" }, { status: 404 })
  }

  const milestones = await query(
    `SELECT id, name, description, progress, status, due_date, created_at
     FROM milestones
     WHERE project_id = $1
     ORDER BY due_date NULLS LAST, created_at ASC`,
    [id],
  )

  const deliverables = await query(
    `SELECT d.id, d.name, d.description, d.file_url, d.file_type, d.status,
            d.review_notes, d.created_at, d.milestone_id
     FROM deliverables d
     JOIN milestones m ON m.id = d.milestone_id
     WHERE m.project_id = $1
     ORDER BY d.created_at DESC`,
    [id],
  )

  return NextResponse.json({
    project: project.rows[0],
    milestones: milestones.rows,
    deliverables: deliverables.rows,
  })
}
