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:

    @staticmethod
    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.
        """
        from configuration.models import SiteConfiguration
        
        # Use order currency or fall back to site configuration
        currency = order.get_currency().lower()
        
        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": currency,
                    "product_data": {
                        "name": f"Order #{order.id}",
                    },
                    "unit_amount": int(order.total_price * 100),  # amount in smallest currency unit
                },
                "quantity": 1,
            }],
        )

        return session

    @staticmethod
    def cancel_checkout_session(session_id):
        """
        Zruší Stripe Checkout Session.
        Args:
            session_id (str): ID Stripe Checkout Session k zrušení.
        
        Returns:
            stripe.checkout.Session: Zrušená Stripe Checkout Session.
        """
        try:
            session = stripe.checkout.Session.expire(session_id)
            return session
        except Exception as e:
            return {"error": str(e)}

    @staticmethod
    def get_checkout_session(session_id):
        """
        Získá informace o Stripe Checkout Session.
        Args:
            session_id (str): ID Stripe Checkout Session.
        
        Returns:
            stripe.checkout.Session: Stripe Checkout Session objekt.
        """
        try:
            session = stripe.checkout.Session.retrieve(session_id)
            return session
        except Exception as e:
            return {"error": str(e)}

    @staticmethod
    def get_payment_intent(payment_intent_id):
        """
        Získá informace o Stripe Payment Intent.
        Args:
            payment_intent_id (str): ID Stripe Payment Intent.
        
        Returns:
            stripe.PaymentIntent: Stripe Payment Intent objekt.
        """
        try:
            payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
            return payment_intent
        except Exception as e:
            return {"error": str(e)}

    @staticmethod
    def refund_order(stripe_payment_intent):
        """
        Vrátí platbu pro danou objednávku.
        Args:
            stripe_payment_intent (str): ID Stripe Payment Intent k vrácení.
        
        Returns:
            stripe.Refund: Vytvořený refund objekt nebo chyba.
        """
        try:
            refund = stripe.Refund.create(
                payment_intent=stripe_payment_intent
            )
            return refund
        
        except Exception as e:
            return {"error": str(e)}

    @staticmethod
    def partial_refund_order(stripe_payment_intent, amount):
        """
        Částečně vrátí platbu pro danou objednávku.
        Args:
            stripe_payment_intent (str): ID Stripe Payment Intent k vrácení.
            amount (int): Částka k vrácení v haléřích.
        
        Returns:
            stripe.Refund: Vytvořený refund objekt nebo chyba.
        """
        try:
            refund = stripe.Refund.create(
                payment_intent=stripe_payment_intent,
                amount=amount
            )
            return refund
        
        except Exception as e:
            return {"error": str(e)}

    @staticmethod
    def create_customer(email, name=None, phone=None):
        """
        Vytvoří Stripe Customer.
        Args:
            email (str): Email zákazníka.
            name (str, optional): Jméno zákazníka.
            phone (str, optional): Telefon zákazníka.
        
        Returns:
            stripe.Customer: Vytvořený Stripe Customer.
        """
        try:
            customer_data = {"email": email}
            if name:
                customer_data["name"] = name
            if phone:
                customer_data["phone"] = phone
                
            customer = stripe.Customer.create(**customer_data)
            return customer
        except Exception as e:
            return {"error": str(e)}

    @staticmethod
    def webhook_verify_signature(payload, sig_header, endpoint_secret):
        """
        Ověří webhook signature od Stripe.
        Args:
            payload: Raw webhook payload.
            sig_header: Stripe signature header.
            endpoint_secret: Webhook endpoint secret.
        
        Returns:
            stripe.Event: Ověřený event objekt.
        """
        try:
            event = stripe.Webhook.construct_event(
                payload, sig_header, endpoint_secret
            )
            return event
        except ValueError as e:
            return {"error": "Invalid payload"}
        except stripe.error.SignatureVerificationError as e:
            return {"error": "Invalid signature"}