import stripe
from django.conf import settings
import json
import os

FRONTEND_URL = os.getenv("FRONTEND_URL") if not settings.DEBUG else os.getenv("DEBUG_DOMAIN")
SSL = "https://" if os.getenv("USE_SSL") == "true" else "http://"

stripe.api_key = os.getenv("STRIPE_SECRET_KEY")

class StripeClient:

    def create_checkout_session(order):
        """
        Vytvoří Stripe Checkout Session pro danou objednávku.
        Args:
            order (Order): Instance objednávky pro kterou se vytváří session.
        
        Returns:
            stripe.checkout.Session: Vytvořená Stripe Checkout Session.
        """

        session = stripe.checkout.Session.create(
            mode="payment",
            payment_method_types=["card"],

            success_url=f"{SSL}{FRONTEND_URL}/payment/success?order={order.id}", #jenom na grafickou část (webhook reálně ověří stav)
            cancel_url=f"{SSL}{FRONTEND_URL}/payment/cancel?order={order.id}",

            client_reference_id=str(order.id),
            line_items=[{
                "price_data": {
                    "currency": "czk",
                    "product_data": {
                        "name": f"Objednávka {order.id}",
                    },
                    "unit_amount": int(order.total_price * 100),  # cena v haléřích
                },
                "quantity": 1,
            }],
        )

        return session


    def refund_order(stripe_payment_intent):
        try:
            refund = stripe.Refund.create(
                payment_intent=stripe_payment_intent
            )
            return refund
        
        except Exception as e:
            return json.dumps({"error": str(e)})