import stripe
from django.conf import settings
from .models import StripeLog
from django.utils.timezone import now
stripe.api_key = settings.STRIPE_SECRET_KEY

def create_checkout_session(account_id, username, email, acore_ip, amount, character_name, currency="eur", success_url=None, cancel_url=None, product_name=""):
    try:
        # 🔹 Crear sesión de pago en Stripe
        session = stripe.checkout.Session.create(
            payment_method_types=["card"],
            line_items=[{
                "price_data": {
                    "currency": currency,
                    "product_data": {"name": product_name}, 
                    "unit_amount": int(amount * 100),
                },
                "quantity": 1,
            }],
            mode="payment",
            success_url=success_url,
            cancel_url=cancel_url,
        )

        # 🔹 Determinar si Stripe está en modo TEST o LIVE
        mode = "live" if settings.STRIPE_SECRET_KEY.startswith("sk_live") else "test"

        # 🔹 Guardar el log en la base de datos
        StripeLog.objects.create(
            account_id=account_id,
            username=username,
            email=email,
            acore_ip=acore_ip,
            stripe_ip=None,  # Se actualizará cuando llegue el webhook
            product_name=product_name,
            amount=amount,
            session_id=session.id,
            mode=mode,
            character_name=character_name,
            timestamp=now()
        )

        return {"success": True, "session_id": session.id}
    
    except Exception as e:
        return {"success": False, "error": str(e)}