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

export async function POST(
  request: NextRequest,
  { 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 body = await request.json()
  const { action, review_notes } = body

  if (!["approve", "reject"].includes(action)) {
    return NextResponse.json({ error: "Action must be 'approve' or 'reject'" }, { status: 400 })
  }

  const milestone = await query(
    `SELECT m.id, m.status, m.project_id
     FROM milestones m
     JOIN projects p ON p.id = m.project_id
     WHERE m.id = $1 AND p.customer_id = $2 AND p.deleted_at IS NULL`,
    [id, session.customerId],
  )

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

  if (milestone.rows[0].status !== "awaiting_approval") {
    return NextResponse.json(
      { error: "Milestone is not awaiting approval" },
      { status: 400 },
    )
  }

  const newStatus = action === "approve" ? "approved" : "rejected"
  const newProgress = action === "approve" ? 100 : 0

  await query(
    `UPDATE milestones
     SET status = $1, progress = $2, updated_at = NOW()
     WHERE id = $3`,
    [newStatus, newProgress, id],
  )

  const deliverableStatus = action === "approve" ? "approved" : "rejected"
  await query(
    `UPDATE deliverables
     SET status = $1, reviewed_at = NOW(), review_notes = $2, updated_at = NOW()
     WHERE milestone_id = $3 AND status = 'pending_review'`,
    [deliverableStatus, review_notes || null, id],
  )

  const updated = await query(
    `SELECT id, name, description, progress, status, due_date, created_at
     FROM milestones WHERE id = $1`,
    [id],
  )

  return NextResponse.json({ milestone: updated.rows[0] })
}
