import httpx
from core.models import ThawaniConfiguration
from django.conf import settings

class ThawaniClient:
    def __init__(self):
        config = ThawaniConfiguration.objects.first()
        if not config:
            # Fallback or error if not configured
            self.api_key = None
            self.publishable_key = None
            self.is_sandbox = True
        else:
            self.api_key = config.api_key
            self.publishable_key = config.publishable_key
            self.is_sandbox = config.is_sandbox
        
        if self.is_sandbox:
            self.base_url = "https://uat-checkout.thawani.om/api/v1"
        else:
            self.base_url = "https://checkout.thawani.om/api/v1"

    def create_checkout_session(self, product, user, success_url, cancel_url):
        if not self.api_key:
            raise Exception("Thawani API Key is not configured.")

        url = f"{self.base_url}/checkout/session"
        headers = {
            "thawani-api-key": self.api_key,
            "Content-Type": "application/json"
        }
        
        # Thawani expects amount in Baisa (1 OMR = 1000 Baisa)
        amount_baisa = int(product.price * 1000)
        
        metadata = {
            "user_id": str(user.id)
        }
        
        # Handle Subject or Package
        # Package has 'subjects' ManyToMany field
        if hasattr(product, 'subjects'): 
             metadata["package_id"] = str(product.id)
        else:
             metadata["subject_id"] = str(product.id)

        payload = {
            "client_reference_id": str(user.id),
            "mode": "payment",
            "products": [
                {
                    "name": product.name_en,
                    "quantity": 1,
                    "unit_amount": amount_baisa
                }
            ],
            "success_url": success_url,
            "cancel_url": cancel_url,
            "metadata": metadata
        }
        
        response = httpx.post(url, json=payload, headers=headers)
        response.raise_for_status()
        return response.json()

    def get_checkout_session(self, session_id):
        if not self.api_key:
            raise Exception("Thawani API Key is not configured.")

        url = f"{self.base_url}/checkout/session/{session_id}"
        headers = {
            "thawani-api-key": self.api_key
        }
        
        response = httpx.get(url, headers=headers)
        response.raise_for_status()
        return response.json()