import stripe
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

class StripeService:
    """Service class to manage Stripe operations with mode awareness"""

    def __init__(self):
        # Determine if we're in test mode
        self.mode = getattr(settings, 'STRIPE_MODE', 'test')
        self.is_test_mode = self.mode == 'test'

        # Get appropriate keys based on mode
        self.api_key = settings.STRIPE_SECRET_KEY
        self.publishable_key = settings.STRIPE_PUBLISHABLE_KEY
        self.webhook_secret = settings.STRIPE_WEBHOOK_SECRET
        self.currency = getattr(settings, 'STRIPE_CURRENCY', 'eur')

        # Configure Stripe library
        stripe.api_key = self.api_key

        # Log initialization in debug mode
        mode_str = "TEST" if self.is_test_mode else "LIVE"
        logger.debug(f"Initialized StripeService in {mode_str} mode")

    def create_checkout_session(self, customer_email, line_items, success_url, cancel_url, metadata=None):
        """Create a Stripe Checkout Session for one-time payments"""
        if self.is_test_mode:
            logger.info(f"Creating checkout session in TEST mode with metadata: {metadata}")

        session = stripe.checkout.Session.create(
            customer_email=customer_email,
            payment_method_types=['card'],
            line_items=line_items,
            mode='payment',
            success_url=success_url,
            cancel_url=cancel_url,
            metadata=metadata or {},
        )
        return session

    def verify_webhook_signature(self, payload, signature):
        """Verify webhook signature using mode-appropriate secret"""
        try:
            event = stripe.Webhook.construct_event(
                payload, signature, self.webhook_secret
            )
            return event
        except stripe.error.SignatureVerificationError as e:
            logger.error(f"Webhook signature verification failed: {str(e)}")
            raise

    def construct_event_for_testing(self, payload, signature):
        """Helper method to construct events during testing"""
        return stripe.Webhook.construct_event(
            payload, signature, self.webhook_secret
        )

    def get_checkout_session(self, session_id):
        """Retrieve a checkout session by ID"""
        return stripe.checkout.Session.retrieve(session_id)

    def get_payment_intent(self, payment_intent_id):
        """Retrieve a payment intent by ID"""
        return stripe.PaymentIntent.retrieve(payment_intent_id)

# Create a singleton instance for import and use throughout the app
stripe_service = StripeService()
