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

// Check if user has purchased this video
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get("user_id")

    if (!userId) {
      return NextResponse.json({ purchased: false })
    }

    const result = await sql`
      SELECT id FROM purchases
      WHERE user_id = ${userId}
        AND item_id = ${id}
        AND item_type = 'video'
        AND status = 'completed'
      LIMIT 1
    `

    return NextResponse.json({ purchased: result.length > 0 })
  } catch (error: any) {
    console.error("[Video Purchase Check] Error:", error)
    return NextResponse.json({ error: "Failed to check purchase" }, { status: 500 })
  }
}

// Create a purchase for this video
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()
    const { user_id, payment_method = "mobile_money" } = body

    if (!user_id) {
      return NextResponse.json({ error: "User ID is required" }, { status: 400 })
    }

    // Get video details
    const videoResult = await sql`
      SELECT id, title, price_fcfa, is_free FROM videos WHERE id = ${id}
    `

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

    const video = videoResult[0]

    if (video.is_free) {
      return NextResponse.json({ error: "This video is free" }, { status: 400 })
    }

    // Check if already purchased
    const existingPurchase = await sql`
      SELECT id FROM purchases
      WHERE user_id = ${user_id}
        AND item_id = ${id}
        AND item_type = 'video'
        AND status = 'completed'
      LIMIT 1
    `

    if (existingPurchase.length > 0) {
      return NextResponse.json({ error: "Video already purchased" }, { status: 400 })
    }

    // Create purchase record
    const purchaseResult = await sql`
      INSERT INTO purchases (
        user_id, item_type, item_id, amount, currency, payment_method, status
      )
      VALUES (
        ${user_id}, 'video', ${id}, ${video.price_fcfa}, 'XAF', ${payment_method}, 'completed'
      )
      RETURNING *
    `

    return NextResponse.json({ 
      success: true, 
      purchase: purchaseResult[0],
      message: "Video purchased successfully" 
    })
  } catch (error: any) {
    console.error("[Video Purchase] Error:", error)
    return NextResponse.json({ error: "Failed to purchase video" }, { status: 500 })
  }
}
