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

function stageToStatus(name: string): string {
  switch (name) {
    case "New": return "open"
    case "Contacted": return "contacted"
    case "Qualified":
    case "Interested":
    case "Demo Scheduled":
    case "Negotiation": return "pending"
    case "Closed Won": return "closed"
    case "Closed Lost": return "ignored"
    default: return "open"
  }
}

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 l.id, l.company_name, l.contact_name, l.email, l.phone, l.score,
              l.assigned_to, l.created_at, l.updated_at, l.notes, l.source_id,
              ls.name AS stage_name,
              u.id AS user_id, u.first_name, u.last_name, u.email AS user_email, u.avatar_url
       FROM leads l
       JOIN lead_stages ls ON ls.id = l.stage_id
       LEFT JOIN users u ON u.id = l.assigned_to
       WHERE l.id = $1 AND l.deleted_at IS NULL`,
      [id]
    )

    if (result.rows.length === 0) {
      return NextResponse.json({ error: "Lead not found" }, { status: 404 })
    }

    const r = result.rows[0]
    const lead = {
      id: r.id,
      companyName: r.company_name || "",
      contactName: r.contact_name,
      email: r.email || "",
      phone: r.phone || "",
      source: "",
      description: r.notes || "",
      status: stageToStatus(r.stage_name),
      assignedUserId: r.assigned_to,
      assignedUser: r.assigned_to ? {
        id: r.user_id,
        name: `${r.first_name} ${r.last_name}`,
        email: r.user_email,
        avatar: r.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(`${r.first_name} ${r.last_name}`)}&background=1d4ed8&color=fff&size=128`,
      } : null,
      createdAt: r.created_at,
      updatedAt: r.updated_at,
    }

    return NextResponse.json(lead)
  } catch (error) {
    console.error("Lead detail API error:", error)
    return NextResponse.json({ error: "Failed to load lead" }, { status: 500 })
  }
}
