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

export async function POST(request: NextRequest) {
  try {
    const { userId, planId, billingCycle = "monthly" } = await request.json()

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

    // Get plan details
    const plans = await sql`
      SELECT * FROM subscription_plans WHERE slug = ${planId} AND is_active = true
    `

    if (plans.length === 0) {
      return NextResponse.json({ error: "Plan non trouvé" }, { status: 404 })
    }

    const plan = plans[0]
    const amount = billingCycle === "yearly" ? plan.price_yearly : plan.price_monthly

    // Check if user already has an active subscription
    const existingSubs = await sql`
      SELECT * FROM user_subscriptions 
      WHERE user_id = ${userId} 
      AND status IN ('active', 'trialing')
    `

    if (existingSubs.length > 0) {
      // Update existing subscription
      await sql`
        UPDATE user_subscriptions
        SET plan_id = ${plan.id},
            status = 'active',
            current_period_start = CURRENT_TIMESTAMP,
            current_period_end = CURRENT_TIMESTAMP + INTERVAL '1 month',
            updated_at = CURRENT_TIMESTAMP
        WHERE user_id = ${userId} AND status IN ('active', 'trialing')
      `
    } else {
      // Create new subscription
      await sql`
        INSERT INTO user_subscriptions (user_id, plan_id, status, current_period_start, current_period_end)
        VALUES (
          ${userId}, 
          ${plan.id}, 
          'active',
          CURRENT_TIMESTAMP,
          CURRENT_TIMESTAMP + INTERVAL '1 month'
        )
      `
    }

    // Update user subscription type
    await sql`
      UPDATE users 
      SET subscription_type = ${plan.slug},
          subscription_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 month',
          updated_at = CURRENT_TIMESTAMP
      WHERE id = ${userId}
    `

    // Create payment transaction record
    await sql`
      INSERT INTO payment_transactions (
        user_id,
        amount,
        currency,
        status,
        description,
        payment_method
      ) VALUES (
        ${userId},
        ${amount},
        'XOF',
        'completed',
        ${`Abonnement ${plan.name} - ${billingCycle === "yearly" ? "Annuel" : "Mensuel"}`},
        'card'
      )
    `

    return NextResponse.json({
      success: true,
      message: "Abonnement activé avec succès",
      subscription: {
        plan: plan.name,
        status: "active",
        expires_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
      },
    })
  } catch (error) {
    console.error("Subscription upgrade error:", error)
    return NextResponse.json({ error: "Erreur lors de la mise à niveau" }, { status: 500 })
  }
}
