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

export async function POST(request: NextRequest) {
  try {
    const authHeader = request.headers.get("authorization")
    const token = authHeader?.replace("Bearer ", "")

    if (!token) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 })
    }

    // Verify user session
    const session = await sql`
      SELECT user_id FROM user_sessions
      WHERE token = ${token} AND expires_at > NOW()
    `

    if (session.length === 0) {
      return NextResponse.json({ error: "Session invalide" }, { status: 401 })
    }

    const userId = session[0].user_id
    const { connectionType, effectiveBandwidth, qualitySelected } = await request.json()

    // Log network quality
    await sql`
      INSERT INTO network_quality_logs (user_id, connection_type, effective_bandwidth_mbps, quality_selected)
      VALUES (${userId}, ${connectionType}, ${effectiveBandwidth}, ${qualitySelected})
    `

    // Recommend quality based on bandwidth
    let recommendedQuality = "normal"
    if (effectiveBandwidth >= 2) {
      recommendedQuality = "very_high"
    } else if (effectiveBandwidth >= 1) {
      recommendedQuality = "high"
    } else if (effectiveBandwidth >= 0.5) {
      recommendedQuality = "normal"
    } else {
      recommendedQuality = "low"
    }

    return NextResponse.json({
      recommendedQuality,
      bandwidth: effectiveBandwidth,
      connectionType,
    })
  } catch (error) {
    console.error("Network quality log error:", error)
    return NextResponse.json({ error: "Erreur lors de l'enregistrement de la qualité réseau" }, { status: 500 })
  }
}
