import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()
    const { user_id } = body

    // Record the view
    if (user_id) {
      await sql`
        INSERT INTO video_views (video_id, user_id)
        VALUES (${id}, ${user_id})
        ON CONFLICT DO NOTHING
      `
    }

    // Increment view count
    await sql`
      UPDATE videos
      SET view_count = view_count + 1
      WHERE id = ${id}
    `

    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error("[Video View API] Error:", error)
    return NextResponse.json({ error: "Failed to record view" }, { status: 500 })
  }
}
