// ── Conversations: Mark as Read ─────────────────────────────────────────────
// POST /api/conversations/[id]/read
//   — Updates the current user's last_read_at timestamp for the conversation.
//   — Also marks all related (unread) notifications for this conversation as read.
//
// Auth: authenticated; user must be a participant

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

// ── 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

    // Update the participant's last_read_at to now
    await query(
      `UPDATE conversation_participants
       SET last_read_at = NOW()
       WHERE conversation_id = $1 AND user_id = $2`,
      [id, user.id],
    )

    // Clear any existing notifications for this conversation
    await query(
      `UPDATE notifications SET is_read = TRUE
       WHERE user_id = $1 AND context_type = 'conversation' AND context_id = $2 AND is_read = FALSE`,
      [user.id, id],
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Mark read error:", error)
    return NextResponse.json({ error: "Failed to mark as read" }, { status: 500 })
  }
}
