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

export async function POST(request: NextRequest) {
  try {
    const { userId } = await request.json()

    if (!userId) {
      return NextResponse.json({ error: "userId requis" }, { status: 400 })
    }

    // Update subscription to cancel at period end
    await sql`
      UPDATE user_subscriptions
      SET cancel_at_period_end = true,
          updated_at = CURRENT_TIMESTAMP
      WHERE user_id = ${userId} AND status = 'active'
    `

    return NextResponse.json({
      success: true,
      message: "L'abonnement sera annulé à la fin de la période en cours",
    })
  } catch (error) {
    console.error("Subscription cancel error:", error)
    return NextResponse.json({ error: "Erreur lors de l'annulation" }, { status: 500 })
  }
}
