// ── Leads: Notes ─────────────────────────────────────────────────────────────
// POST /api/leads/[id]/notes  — Add a note to a lead
// GET  /api/leads/[id]/notes  — List notes for a lead (paginated)
//
// Auth: authenticated users with access to the lead (owner or admin)

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

// ── Helpers ──────────────────────────────────────────────────────────────────

/**
 * Checks whether the requesting user has access to the given lead.
 * Access is granted if the user is the assigned owner or has an admin role.
 */
async function checkLeadAccess(leadId: string, userId: string): Promise<boolean> {
  const result = await query(
    `SELECT 1 FROM leads WHERE id = $1 AND deleted_at IS NULL
     AND (assigned_to = $2 OR EXISTS (
       SELECT 1 FROM user_roles ur JOIN roles r ON r.id = ur.role_id
       WHERE ur.user_id = $2 AND r.name IN ('ADMIN', 'SUPER_ADMIN')
     ))`,
    [leadId, userId]
  )
  return result.rows.length > 0
}

// ── POST ─────────────────────────────────────────────────────────────────────

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
    if (!await checkLeadAccess(id, user.id)) {
      return NextResponse.json({ error: "Lead not found" }, { status: 404 })
    }

    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 })
  }
}

// ── GET ──────────────────────────────────────────────────────────────────────

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
    if (!await checkLeadAccess(id, user.id)) {
      return NextResponse.json({ error: "Lead not found" }, { status: 404 })
    }
    const { searchParams } = new URL(request.url)
    const limit = parseInt(searchParams.get("limit") || "50", 10)
    const offset = parseInt(searchParams.get("offset") || "0", 10)

    // Fetch notes with author info, ordered newest-first
    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
       LIMIT $2 OFFSET $3`,
      [id, limit, offset]
    )

    const notes = result.rows.map((r: any) => ({
      id: r.id,
      leadId: id,
      userId: r.user_id,
      authorName: `${r.first_name} ${r.last_name}`,
      authorAvatar: avatarSvgUrl(`${r.first_name} ${r.last_name}`),
      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 })
  }
}
