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

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 { content } = await request.json()
    if (!content?.trim()) {
      return NextResponse.json({ error: "Content is required" }, { status: 400 })
    }

    await query(
      `INSERT INTO customer_notes (customer_id, author_id, content)
       VALUES ($1, $2, $3)`,
      [id, user.id, content.trim()]
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Create note error:", error)
    return NextResponse.json({ error: "Failed to create note" }, { status: 500 })
  }
}

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 cn.id, cn.created_at, cn.updated_at, cn.content,
              u.id AS user_id, u.first_name, u.last_name, u.avatar_url
       FROM customer_notes cn
       JOIN users u ON u.id = cn.author_id
       WHERE cn.customer_id = $1 AND cn.deleted_at IS NULL
       ORDER BY cn.created_at DESC`,
      [id]
    )

    const notes = result.rows.map((r: any) => ({
      id: r.id,
      leadId: id,
      userId: r.user_id,
      authorName: `${r.first_name} ${r.last_name}`,
      authorAvatar: r.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(`${r.first_name} ${r.last_name}`)}&background=1d4ed8&color=fff&size=128`,
      note: r.content,
      createdAt: r.created_at,
      updatedAt: r.updated_at,
    }))

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