import hashlib
import json
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from core.config import get_settings
from core.exceptions import (
    ConflictError,
    ForbiddenError,
    NotFoundError,
    PaymentError,
    QuotaExceededError,
    UnauthorizedError,
    ValidationError,
)
from core.logging import get_logger
from infrastructure.payments.gateway_factory import GatewayFactory
from modules.billing.coupon_service import CouponService
from modules.billing.entitlement_service import EntitlementService
from modules.billing.models import (
    Invoice,
    PaymentOrder,
    PaymentWebhookEvent,
    Plan,
    Refund,
    Subscription,
)
from modules.billing.repository import BillingRepository
from modules.billing.schemas import (
    CheckoutOrderRequest,
    CheckoutOrderResponse,
    InvoiceResponse,
    PaymentVerificationRequest,
    PaymentVerificationResponse,
    PlanResponse,
    RefundRequest,
    RefundResponse,
    SubscriptionResponse,
)
from modules.billing.wallet_service import WalletService
from modules.tenants.models import Tenant

logger = get_logger(__name__)


class BillingService:
    """Core enterprise billing, subscriptions, invoices, and payment orchestration service."""

    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = BillingRepository(db)
        self.entitlements = EntitlementService(db)
        self.wallets = WalletService(db)
        self.coupons = CouponService(db)

    # --- Seed Default Plans ---
    async def seed_default_plans(self) -> None:
        """Seeds the 4 standard commercial tiers if not already populated."""
        default_plans = [
            Plan(
                id="free",
                name="Free Tier",
                description="Essential features to test and run your first Telegram bot.",
                price_amount=0,
                currency="INR",
                billing_interval="monthly",
                trial_days=0,
                is_active=True,
                max_bots=1,
                max_broadcasts_per_month=100,
                max_custom_emojis=10,
                ai_enabled=False,
                advanced_studio=False,
                custom_domain=False,
                priority_support=False,
                webhook_rate_limit=10,
            ),
            Plan(
                id="starter",
                name="Starter Plan",
                description="Designed for creators running up to 3 bots with custom styling.",
                price_amount=99900,  # ₹999.00
                currency="INR",
                billing_interval="monthly",
                trial_days=7,
                is_active=True,
                max_bots=3,
                max_broadcasts_per_month=2500,
                max_custom_emojis=50,
                ai_enabled=False,
                advanced_studio=True,
                custom_domain=False,
                priority_support=False,
                webhook_rate_limit=30,
            ),
            Plan(
                id="pro",
                name="Pro Supercharged",
                description="Full AI integration, advanced Message Studio, and up to 10 bots.",
                price_amount=299900,  # ₹2,999.00
                currency="INR",
                billing_interval="monthly",
                trial_days=14,
                is_active=True,
                max_bots=10,
                max_broadcasts_per_month=25000,
                max_custom_emojis=500,
                ai_enabled=True,
                advanced_studio=True,
                custom_domain=False,
                priority_support=True,
                webhook_rate_limit=60,
            ),
            Plan(
                id="enterprise",
                name="Enterprise Max",
                description="Unlimited scale, custom domain, and dedicated infrastructure.",
                price_amount=999900,  # ₹9,999.00
                currency="INR",
                billing_interval="monthly",
                trial_days=14,
                is_active=True,
                max_bots=-1,  # unlimited
                max_broadcasts_per_month=-1,
                max_custom_emojis=-1,
                ai_enabled=True,
                advanced_studio=True,
                custom_domain=True,
                priority_support=True,
                webhook_rate_limit=120,
            ),
        ]
        for plan in default_plans:
            await self.repo.upsert_plan(plan)

    # --- Plans Catalog ---
    async def list_plans(self) -> list[PlanResponse]:
        plans = await self.repo.list_active_plans()
        if not plans:
            await self.seed_default_plans()
            plans = await self.repo.list_active_plans()

        return [
            PlanResponse(
                id=p.id,
                name=p.name,
                description=p.description,
                price_amount=p.price_amount,
                price_formatted=f"₹{p.price_amount / 100:.2f}" if p.currency == "INR" else f"${p.price_amount / 100:.2f}",
                currency=p.currency,
                billing_interval=p.billing_interval,
                trial_days=p.trial_days,
                is_active=p.is_active,
                max_bots=p.max_bots,
                max_broadcasts_per_month=p.max_broadcasts_per_month,
                max_custom_emojis=p.max_custom_emojis,
                ai_enabled=p.ai_enabled,
                advanced_studio=p.advanced_studio,
                custom_domain=p.custom_domain,
                priority_support=p.priority_support,
                webhook_rate_limit=p.webhook_rate_limit,
            )
            for p in plans
        ]

    # --- Subscriptions ---
    async def get_tenant_subscription(self, tenant_id: uuid.UUID) -> SubscriptionResponse:
        plan, sub = await self.entitlements.get_tenant_plan_and_sub(tenant_id)
        return SubscriptionResponse(
            id=sub.id,
            tenant_id=sub.tenant_id,
            plan_id=sub.plan_id,
            plan_name=plan.name,
            status=sub.status,
            current_period_start=sub.current_period_start,
            current_period_end=sub.current_period_end,
            cancel_at_period_end=sub.cancel_at_period_end,
            canceled_at=sub.canceled_at,
            trial_start=sub.trial_start,
            trial_end=sub.trial_end,
            grace_period_ends_at=sub.grace_period_ends_at,
            gateway_provider=sub.gateway_provider,
        )

    # --- Checkout & Order Creation ---
    async def create_checkout_order(
        self,
        tenant_id: uuid.UUID,
        req: CheckoutOrderRequest,
    ) -> CheckoutOrderResponse:
        """
        Creates a payment order with idempotency guarantee and gateway integration.
        """
        plan = await self.repo.get_plan_by_id(req.plan_id)
        if not plan:
            raise NotFoundError(f"Plan '{req.plan_id}' does not exist")

        idempotency_key = req.idempotency_key or f"idem_{tenant_id}_{req.plan_id}_{uuid.uuid4().hex[:12]}"
        existing_order = await self.repo.get_order_by_idempotency_key(idempotency_key)
        if existing_order and existing_order.status == "created":
            return CheckoutOrderResponse(
                order_id=existing_order.id,
                order_number=existing_order.order_number,
                amount=existing_order.amount,
                amount_formatted=f"₹{existing_order.amount / 100:.2f}",
                currency=existing_order.currency,
                provider=existing_order.provider,
                gateway_order_id=existing_order.gateway_order_id,
                status=existing_order.status,
            )

        # Discount calculation
        final_amount = plan.price_amount
        coupon_id = None
        discount_applied = 0
        if req.coupon_code:
            is_valid, coupon, discount, _ = await self.coupons.validate_coupon(
                req.coupon_code, plan.id, plan.price_amount
            )
            if is_valid and coupon:
                discount_applied = discount
                final_amount = max(0, plan.price_amount - discount)
                coupon_id = str(coupon.id)

        now_str = datetime.now(timezone.utc).strftime("%Y%m%d")
        order_number = f"ORD-{now_str}-{uuid.uuid4().hex[:8].upper()}"

        gateway_order_id = None
        gateway_key_id = None
        checkout_url = None

        if req.provider in ("razorpay", "stripe") and final_amount > 0:
            gateway = GatewayFactory.get_gateway(req.provider)
            gw_resp = await gateway.create_order(
                amount=final_amount,
                currency=plan.currency,
                receipt=order_number,
                notes={
                    "tenant_id": str(tenant_id),
                    "plan_id": plan.id,
                    "plan_name": plan.name,
                    "order_number": order_number,
                },
                idempotency_key=idempotency_key,
            )
            gateway_order_id = gw_resp.get("id")
            gateway_key_id = gw_resp.get("key_id")
            checkout_url = gw_resp.get("url")

        order = await self.repo.create_order(
            tenant_id=tenant_id,
            order_number=order_number,
            amount=final_amount,
            currency=plan.currency,
            provider=req.provider,
            idempotency_key=idempotency_key,
            purpose="subscription",
            plan_id=plan.id,
            gateway_order_id=gateway_order_id,
            metadata_json={
                "coupon_id": coupon_id,
                "discount_applied": discount_applied,
                "original_amount": plan.price_amount,
                "plan_name": plan.name,
            },
        )

        return CheckoutOrderResponse(
            order_id=order.id,
            order_number=order.order_number,
            amount=order.amount,
            amount_formatted=f"₹{order.amount / 100:.2f}" if order.currency == "INR" else f"${order.amount / 100:.2f}",
            currency=order.currency,
            provider=order.provider,
            gateway_order_id=gateway_order_id,
            gateway_key_id=gateway_key_id,
            checkout_url=checkout_url,
            status=order.status,
        )

    # --- Server-Side Payment Verification & Activation ---
    async def verify_and_activate_payment(
        self,
        tenant_id: uuid.UUID,
        req: PaymentVerificationRequest,
    ) -> PaymentVerificationResponse:
        """
        Server-side cryptographic verification of payment completion.
        Never trusts client-reported success without gateway signature confirmation.
        """
        order = await self.repo.get_order_by_id(req.order_id)
        if not order:
            raise NotFoundError("Order not found")

        if order.tenant_id != tenant_id:
            raise ForbiddenError("Cross-tenant order verification forbidden")

        if order.status == "paid":
            # Idempotent response
            sub = await self.repo.get_tenant_subscription(tenant_id)
            return PaymentVerificationResponse(
                success=True,
                message="Payment already verified and subscription active",
                order_id=order.id,
                status="paid",
                subscription_id=sub.id if sub else uuid.uuid4(),
            )

        # Verify signature with gateway
        gateway = GatewayFactory.get_gateway(req.provider)
        gateway_order_id = order.gateway_order_id or str(order.id)
        is_valid = gateway.verify_payment_signature(
            order_id=gateway_order_id,
            payment_id=req.payment_id,
            signature=req.signature or "",
        )

        if not is_valid:
            await self.repo.update_order(order, status="failed", gateway_payment_id=req.payment_id)
            logger.warning("payment_signature_verification_failed", order_id=str(order.id), payment_id=req.payment_id)
            raise PaymentError("Cryptographic payment signature verification failed")

        # Mark order paid
        await self.repo.update_order(
            order,
            status="paid",
            gateway_payment_id=req.payment_id,
            gateway_signature=req.signature,
        )

        # Activate Subscription
        now = datetime.now(timezone.utc)
        period_end = now + timedelta(days=30)
        sub = await self.repo.get_tenant_subscription(tenant_id)
        if sub:
            await self.repo.update_subscription(
                sub,
                plan_id=order.plan_id or "starter",
                status="active",
                current_period_start=now,
                current_period_end=period_end,
                cancel_at_period_end=False,
                grace_period_ends_at=None,
                gateway_provider=req.provider,
                gateway_subscription_id=req.payment_id,
            )
        else:
            sub = await self.repo.create_subscription(
                tenant_id=tenant_id,
                plan_id=order.plan_id or "starter",
                status="active",
                current_period_start=now,
                current_period_end=period_end,
                gateway_provider=req.provider,
            )

        # Update tenant model plan_id
        await self.db.execute(
            select(Tenant).where(Tenant.id == tenant_id)
        )
        tenant_res = await self.db.get(Tenant, tenant_id)
        if tenant_res:
            tenant_res.plan_id = order.plan_id
            await self.db.commit()

        # Generate Invoice
        invoice_number = f"INV-{now.strftime('%Y')}-{uuid.uuid4().hex[:6].upper()}"
        plan = await self.repo.get_plan_by_id(order.plan_id or "starter")
        subtotal = order.amount
        tax = int(subtotal * 0.18)  # 18% GST / VAT
        discount = (order.metadata_json or {}).get("discount_applied", 0)

        invoice = await self.repo.create_invoice(
            tenant_id=tenant_id,
            invoice_number=invoice_number,
            amount_due=order.amount,
            amount_paid=order.amount,
            currency=order.currency,
            status="paid",
            due_date=now,
            paid_at=now,
            billing_email=f"billing@{tenant_id}.saas",
            billing_name=tenant_res.name if tenant_res else "Tenant Organization",
            items=[{
                "description": f"Subscription Plan: {plan.name if plan else order.plan_id} (1 Month)",
                "quantity": 1,
                "unit_price": order.amount,
                "total": order.amount,
            }],
            subtotal=subtotal,
            tax_amount=tax,
            discount_amount=discount,
            subscription_id=sub.id,
            order_id=order.id,
        )

        # Record Coupon Redemption if applied
        coupon_id_str = (order.metadata_json or {}).get("coupon_id")
        if coupon_id_str and discount > 0:
            await self.coupons.record_redemption(
                tenant_id=tenant_id,
                coupon_id=uuid.UUID(coupon_id_str),
                order_id=order.id,
                discount_applied=discount,
            )

        # Trigger referral bonus if tenant was referred and this is their first payment
        referral = await self.repo.get_referral_by_referred_tenant(tenant_id)
        if referral and referral.status == "pending":
            referral.status = "rewarded"
            referral.rewarded_at = now
            await self.db.commit()
            # Reward referrer wallet with ₹500 credits
            await self.wallets.credit(
                tenant_id=referral.referrer_tenant_id,
                amount=referral.reward_amount,
                reference_type="referral",
                description=f"Referral reward for inviting tenant {tenant_res.name if tenant_res else str(tenant_id)[:8]}",
                reference_id=str(referral.id),
            )

        return PaymentVerificationResponse(
            success=True,
            message="Payment successfully verified and subscription activated",
            order_id=order.id,
            status="paid",
            subscription_id=sub.id,
            invoice_id=invoice.id,
        )

    # --- Pay with Wallet Balance ---
    async def pay_with_wallet(
        self,
        tenant_id: uuid.UUID,
        plan_id: str,
        coupon_code: Optional[str] = None,
    ) -> PaymentVerificationResponse:
        """Allows tenants to subscribe or renew instantly using prepaid wallet credits."""
        plan = await self.repo.get_plan_by_id(plan_id)
        if not plan:
            raise NotFoundError(f"Plan '{plan_id}' does not exist")

        amount_to_pay = plan.price_amount
        discount_applied = 0
        coupon_id = None
        if coupon_code:
            is_valid, coupon, discount, _ = await self.coupons.validate_coupon(
                coupon_code, plan.id, plan.price_amount
            )
            if is_valid and coupon:
                discount_applied = discount
                amount_to_pay = max(0, plan.price_amount - discount)
                coupon_id = str(coupon.id)

        # Debit wallet atomically
        tx = await self.wallets.debit(
            tenant_id=tenant_id,
            amount=amount_to_pay,
            reference_type="subscription",
            description=f"Wallet payment for plan: {plan.name}",
        )

        now = datetime.now(timezone.utc)
        order_number = f"ORD-{now.strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
        order = await self.repo.create_order(
            tenant_id=tenant_id,
            order_number=order_number,
            amount=amount_to_pay,
            currency=plan.currency,
            provider="wallet",
            idempotency_key=f"wallet_{tx.id}",
            purpose="subscription",
            plan_id=plan.id,
            gateway_order_id=str(tx.id),
            metadata_json={"wallet_tx_id": str(tx.id), "discount_applied": discount_applied},
        )
        await self.repo.update_order(order, status="paid", gateway_payment_id=str(tx.id))

        # Update Subscription
        period_end = now + timedelta(days=30)
        sub = await self.repo.get_tenant_subscription(tenant_id)
        if sub:
            await self.repo.update_subscription(
                sub,
                plan_id=plan.id,
                status="active",
                current_period_start=now,
                current_period_end=period_end,
                cancel_at_period_end=False,
                grace_period_ends_at=None,
                gateway_provider="wallet",
            )
        else:
            sub = await self.repo.create_subscription(
                tenant_id=tenant_id,
                plan_id=plan.id,
                status="active",
                current_period_start=now,
                current_period_end=period_end,
                gateway_provider="wallet",
            )

        # Update tenant plan_id
        tenant_res = await self.db.get(Tenant, tenant_id)
        if tenant_res:
            tenant_res.plan_id = plan.id
            await self.db.commit()

        # Create Invoice
        invoice_num = f"INV-{now.strftime('%Y')}-{uuid.uuid4().hex[:6].upper()}"
        invoice = await self.repo.create_invoice(
            tenant_id=tenant_id,
            invoice_number=invoice_num,
            amount_due=amount_to_pay,
            amount_paid=amount_to_pay,
            currency=plan.currency,
            status="paid",
            due_date=now,
            paid_at=now,
            billing_email=f"billing@{tenant_id}.saas",
            billing_name=tenant_res.name if tenant_res else "Tenant Organization",
            items=[{
                "description": f"Subscription Plan: {plan.name} (Paid via Wallet)",
                "quantity": 1,
                "unit_price": amount_to_pay,
                "total": amount_to_pay,
            }],
            subtotal=amount_to_pay,
            tax_amount=0,
            discount_amount=discount_applied,
            subscription_id=sub.id,
            order_id=order.id,
        )

        return PaymentVerificationResponse(
            success=True,
            message="Payment completed successfully with wallet balance",
            order_id=order.id,
            status="paid",
            subscription_id=sub.id,
            invoice_id=invoice.id,
        )

    # --- Upgrade / Downgrade with Proration ---
    async def upgrade_subscription(
        self,
        tenant_id: uuid.UUID,
        new_plan_id: str,
        provider: str = "razorpay",
        coupon_code: Optional[str] = None,
    ) -> CheckoutOrderResponse:
        """
        Calculates proration credit for unused time on existing plan, creating checkout order for the delta.
        """
        new_plan = await self.repo.get_plan_by_id(new_plan_id)
        if not new_plan:
            raise NotFoundError(f"Target plan '{new_plan_id}' not found")

        old_plan, sub = await self.entitlements.get_tenant_plan_and_sub(tenant_id)
        now = datetime.now(timezone.utc)

        # Calculate unused proration credit
        prorated_credit = 0
        if sub.status == "active" and sub.current_period_end > now and old_plan.price_amount > 0:
            total_seconds = (sub.current_period_end - sub.current_period_start).total_seconds()
            remaining_seconds = (sub.current_period_end - now).total_seconds()
            if total_seconds > 0:
                unused_ratio = max(0.0, min(1.0, remaining_seconds / total_seconds))
                prorated_credit = int(old_plan.price_amount * unused_ratio)

        net_amount = max(0, new_plan.price_amount - prorated_credit)

        # Apply coupon if given
        discount = 0
        if coupon_code:
            is_valid, coupon, d_amt, _ = await self.coupons.validate_coupon(coupon_code, new_plan.id, net_amount)
            if is_valid:
                discount = d_amt
                net_amount = max(0, net_amount - discount)

        idempotency_key = f"upgrade_{tenant_id}_{new_plan_id}_{now.strftime('%Y%m%d%H%M')}"
        req = CheckoutOrderRequest(
            plan_id=new_plan.id,
            provider=provider,
            coupon_code=coupon_code,
            idempotency_key=idempotency_key,
        )
        return await self.create_checkout_order(tenant_id, req)

    async def downgrade_subscription(
        self,
        tenant_id: uuid.UUID,
        new_plan_id: str,
        immediate: bool = False,
    ) -> SubscriptionResponse:
        """
        Verifies usage against new plan limits. If within limits, downgrades immediately or schedules for period end.
        """
        new_plan = await self.repo.get_plan_by_id(new_plan_id)
        if not new_plan:
            raise NotFoundError(f"Target plan '{new_plan_id}' not found")

        # Check resource limits
        if new_plan.max_bots != -1:
            active_bots = await self.repo.count_active_bots(tenant_id)
            if active_bots > new_plan.max_bots:
                raise ValidationError(
                    f"Cannot downgrade to '{new_plan.name}'. You currently have {active_bots} active bot(s), "
                    f"which exceeds the plan limit of {new_plan.max_bots}. Please delete extra bots before downgrading."
                )

        sub = await self.repo.get_tenant_subscription(tenant_id)
        if not sub:
            raise NotFoundError("Subscription not found")

        if immediate:
            await self.repo.update_subscription(sub, plan_id=new_plan.id)
            tenant_res = await self.db.get(Tenant, tenant_id)
            if tenant_res:
                tenant_res.plan_id = new_plan.id
                await self.db.commit()
        else:
            # Scheduled at period end
            await self.repo.update_subscription(sub, cancel_at_period_end=True)

        return await self.get_tenant_subscription(tenant_id)

    # --- Cancellation & Grace Periods & Expiry ---
    async def cancel_subscription(
        self,
        tenant_id: uuid.UUID,
        immediate: bool = False,
    ) -> SubscriptionResponse:
        sub = await self.repo.get_tenant_subscription(tenant_id)
        if not sub:
            raise NotFoundError("Subscription not found")

        now = datetime.now(timezone.utc)
        if immediate:
            await self.repo.update_subscription(
                sub,
                status="canceled",
                canceled_at=now,
                plan_id="free",
            )
            tenant_res = await self.db.get(Tenant, tenant_id)
            if tenant_res:
                tenant_res.plan_id = "free"
                await self.db.commit()
        else:
            await self.repo.update_subscription(
                sub,
                cancel_at_period_end=True,
                canceled_at=now,
            )

        return await self.get_tenant_subscription(tenant_id)

    async def process_subscription_expiry(self, tenant_id: uuid.UUID) -> SubscriptionResponse:
        """
        Checks current_period_end. If expired, transitions through grace_period (3 days) before downgrading to free.
        """
        sub = await self.repo.get_tenant_subscription(tenant_id)
        if not sub:
            raise NotFoundError("Subscription not found")

        now = datetime.now(timezone.utc)
        if now > sub.current_period_end:
            # Check grace period
            if sub.grace_period_ends_at is None:
                # Initiate 3-day grace period
                grace_end = sub.current_period_end + timedelta(days=3)
                await self.repo.update_subscription(
                    sub,
                    status="grace_period",
                    grace_period_ends_at=grace_end,
                )
            elif now > sub.grace_period_ends_at:
                # Grace period expired -> downgrade to free
                await self.repo.update_subscription(
                    sub,
                    status="expired",
                    plan_id="free",
                )
                tenant_res = await self.db.get(Tenant, tenant_id)
                if tenant_res:
                    tenant_res.plan_id = "free"
                    await self.db.commit()

        return await self.get_tenant_subscription(tenant_id)

    # --- Webhooks (Signature Verification & Deduplication) ---
    async def handle_webhook(
        self,
        provider: str,
        payload_bytes: bytes,
        signature: str,
        headers: Optional[dict[str, str]] = None,
    ) -> dict[str, Any]:
        """
        Handles incoming webhook with HMAC signature verification and duplicate event protection.
        """
        gateway = GatewayFactory.get_gateway(provider)
        if not gateway.verify_webhook_signature(payload_bytes, signature, headers):
            logger.warning("webhook_signature_verification_failed", provider=provider)
            raise UnauthorizedError(f"Invalid {provider.title()} webhook signature")

        try:
            payload = json.loads(payload_bytes.decode("utf-8"))
        except Exception:
            raise ValidationError("Malformed JSON payload in webhook")

        # Extract event ID
        event_id = None
        event_type = None

        if provider == "razorpay":
            event_id = (headers or {}).get("x-razorpay-event-id") or payload.get("event_id") or payload.get("id")
            event_type = payload.get("event", "unknown")
            if not event_id:
                event_id = hashlib.sha256(payload_bytes).hexdigest()[:24]
        elif provider == "stripe":
            event_id = payload.get("id")
            event_type = payload.get("type", "unknown")

        if not event_id:
            event_id = str(uuid.uuid4())

        # Duplicate event protection check (Idempotency)
        existing = await self.repo.get_webhook_event(provider, event_id)
        if existing:
            logger.info("webhook_duplicate_event_ignored", provider=provider, event_id=event_id)
            return {"status": "duplicate_event_acknowledged", "event_id": event_id, "processed": False}

        # Record webhook event
        await self.repo.record_webhook_event(
            gateway_provider=provider,
            event_id=event_id,
            event_type=event_type,
            payload=payload,
            status="processed",
        )

        # Dispatch event actions
        if event_type in ("order.paid", "payment.captured", "payment_intent.succeeded", "checkout.session.completed"):
            await self._handle_order_paid_event(provider, payload)
        elif event_type in ("payment.failed", "payment_intent.payment_failed"):
            await self._handle_payment_failed_event(provider, payload)
        elif event_type in ("refund.processed", "charge.refunded"):
            await self._handle_refund_event(provider, payload)

        return {"status": "success", "event_id": event_id, "processed": True}

    async def _handle_order_paid_event(self, provider: str, payload: dict[str, Any]) -> None:
        gateway_order_id = None
        if provider == "razorpay":
            entity = payload.get("payload", {}).get("payment", {}).get("entity", {})
            gateway_order_id = entity.get("order_id")
        elif provider == "stripe":
            data_obj = payload.get("data", {}).get("object", {})
            gateway_order_id = data_obj.get("id")

        if gateway_order_id:
            order = await self.repo.get_order_by_gateway_order_id(gateway_order_id)
            if order and order.status != "paid":
                await self.repo.update_order(order, status="paid")
                sub = await self.repo.get_tenant_subscription(order.tenant_id)
                now = datetime.now(timezone.utc)
                if sub:
                    await self.repo.update_subscription(
                        sub,
                        status="active",
                        plan_id=order.plan_id or "starter",
                        current_period_start=now,
                        current_period_end=now + timedelta(days=30),
                        grace_period_ends_at=None,
                    )

    async def _handle_payment_failed_event(self, provider: str, payload: dict[str, Any]) -> None:
        gateway_order_id = None
        if provider == "razorpay":
            entity = payload.get("payload", {}).get("payment", {}).get("entity", {})
            gateway_order_id = entity.get("order_id")
        elif provider == "stripe":
            data_obj = payload.get("data", {}).get("object", {})
            gateway_order_id = data_obj.get("id")

        if gateway_order_id:
            order = await self.repo.get_order_by_gateway_order_id(gateway_order_id)
            if order:
                await self.repo.update_order(order, status="failed")
                sub = await self.repo.get_tenant_subscription(order.tenant_id)
                if sub and sub.status == "active":
                    # Put into past_due with 3-day grace period
                    now = datetime.now(timezone.utc)
                    await self.repo.update_subscription(
                        sub,
                        status="past_due",
                        grace_period_ends_at=now + timedelta(days=3),
                    )

    async def _handle_refund_event(self, provider: str, payload: dict[str, Any]) -> None:
        pass

    # --- Refunds ---
    async def process_refund(
        self,
        tenant_id: uuid.UUID,
        req: RefundRequest,
    ) -> RefundResponse:
        order = await self.repo.get_order_by_id(req.order_id)
        if not order:
            raise NotFoundError("Order not found")
        if order.tenant_id != tenant_id:
            raise ForbiddenError("Cross-tenant refund forbidden")
        if order.status not in ("paid", "partially_refunded"):
            raise ValidationError(f"Cannot refund order in status '{order.status}'")

        refund_amount = req.amount or order.amount
        if refund_amount <= 0 or refund_amount > order.amount:
            raise ValidationError(f"Invalid refund amount: {refund_amount}")

        gateway_refund_id = None
        if order.provider in ("razorpay", "stripe"):
            gateway = GatewayFactory.get_gateway(order.provider)
            gw_resp = await gateway.create_refund(
                payment_id=order.gateway_payment_id or order.gateway_order_id or "pay_mock",
                amount=refund_amount,
                currency=order.currency,
                reason=req.reason,
            )
            gateway_refund_id = gw_resp.get("id")
        elif order.provider == "wallet":
            # Refund directly back to wallet
            await self.wallets.credit(
                tenant_id=tenant_id,
                amount=refund_amount,
                reference_type="refund",
                description=f"Refund for order #{order.order_number}: {req.reason}",
                reference_id=str(order.id),
            )
            gateway_refund_id = f"wallet_rfnd_{uuid.uuid4().hex[:12]}"

        new_status = "refunded" if refund_amount == order.amount else "partially_refunded"
        await self.repo.update_order(order, status=new_status)

        refund = await self.repo.create_refund(
            tenant_id=tenant_id,
            order_id=order.id,
            amount=refund_amount,
            currency=order.currency,
            reason=req.reason,
            provider=order.provider,
            status="processed",
            gateway_refund_id=gateway_refund_id,
        )

        return RefundResponse(
            id=refund.id,
            order_id=refund.order_id,
            amount=refund.amount,
            currency=refund.currency,
            status=refund.status,
            gateway_refund_id=refund.gateway_refund_id,
            reason=refund.reason,
        )

    # --- Invoices ---
    async def list_invoices(self, tenant_id: uuid.UUID) -> list[InvoiceResponse]:
        invoices = await self.repo.list_tenant_invoices(tenant_id)
        return [
            InvoiceResponse(
                id=inv.id,
                invoice_number=inv.invoice_number,
                subscription_id=inv.subscription_id,
                order_id=inv.order_id,
                amount_due=inv.amount_due,
                amount_paid=inv.amount_paid,
                amount_remaining=inv.amount_remaining,
                currency=inv.currency,
                status=inv.status,
                due_date=inv.due_date,
                paid_at=inv.paid_at,
                billing_email=inv.billing_email,
                billing_name=inv.billing_name,
                items=inv.items,
                subtotal=inv.subtotal,
                tax_amount=inv.tax_amount,
                discount_amount=inv.discount_amount,
                pdf_url=inv.pdf_url,
            )
            for inv in invoices
        ]

    async def get_invoice(self, tenant_id: uuid.UUID, invoice_id: uuid.UUID) -> InvoiceResponse:
        inv = await self.repo.get_invoice_by_id(invoice_id, tenant_id)
        if not inv:
            raise NotFoundError("Invoice not found")
        return InvoiceResponse(
            id=inv.id,
            invoice_number=inv.invoice_number,
            subscription_id=inv.subscription_id,
            order_id=inv.order_id,
            amount_due=inv.amount_due,
            amount_paid=inv.amount_paid,
            amount_remaining=inv.amount_remaining,
            currency=inv.currency,
            status=inv.status,
            due_date=inv.due_date,
            paid_at=inv.paid_at,
            billing_email=inv.billing_email,
            billing_name=inv.billing_name,
            items=inv.items,
            subtotal=inv.subtotal,
            tax_amount=inv.tax_amount,
            discount_amount=inv.discount_amount,
            pdf_url=inv.pdf_url,
        )

    def render_invoice_html(self, invoice: Invoice) -> str:
        """Renders a clean, print-ready HTML invoice."""
        date_str = invoice.due_date.strftime("%B %d, %Y")
        paid_str = invoice.paid_at.strftime("%B %d, %Y") if invoice.paid_at else "Pending"
        currency_sym = "₹" if invoice.currency == "INR" else "$"

        rows_html = ""
        for item in invoice.items:
            unit_val = f"{currency_sym}{item.get('unit_price', 0) / 100:.2f}"
            tot_val = f"{currency_sym}{item.get('total', 0) / 100:.2f}"
            rows_html += f"""
            <tr>
                <td style="padding: 12px; border-bottom: 1px solid #e2e8f0;">{item.get('description', '')}</td>
                <td style="padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: center;">{item.get('quantity', 1)}</td>
                <td style="padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: right;">{unit_val}</td>
                <td style="padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: right; font-weight: 600;">{tot_val}</td>
            </tr>
            """

        status_color = "#16a34a" if invoice.status == "paid" else "#ea580c"

        return f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Invoice {invoice.invoice_number}</title>
    <style>
        body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; margin: 0; padding: 40px; background-color: #f8fafc; }}
        .invoice-card {{ max-width: 800px; margin: 0 auto; background: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); padding: 48px; border: 1px solid #e2e8f0; }}
        .header {{ display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 36px; }}
        .brand {{ font-size: 24px; font-weight: 800; color: #0f172a; letter-spacing: -0.5px; }}
        .badge {{ display: inline-block; padding: 4px 12px; border-radius: 9999px; font-size: 13px; font-weight: 700; text-transform: uppercase; background-color: {status_color}20; color: {status_color}; }}
        .meta-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 36px; padding: 24px; background: #f8fafc; border-radius: 8px; }}
        table {{ width: 100%; border-collapse: collapse; margin-bottom: 36px; }}
        th {{ text-align: left; padding: 12px; border-bottom: 2px solid #cbd5e1; font-size: 13px; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; }}
        .totals {{ margin-left: auto; width: 300px; }}
        .total-row {{ display: flex; justify-content: space-between; padding: 8px 0; font-size: 14px; color: #64748b; }}
        .total-row.grand {{ font-size: 18px; font-weight: 800; color: #0f172a; border-top: 2px solid #e2e8f0; padding-top: 12px; }}
    </style>
</head>
<body>
    <div class="invoice-card">
        <div class="header">
            <div>
                <div class="brand">⚡ Telegram SaaS Platform</div>
                <div style="color: #64748b; margin-top: 4px; font-size: 14px;">Enterprise Bot Infrastructure</div>
            </div>
            <div style="text-align: right;">
                <div class="badge">{invoice.status}</div>
                <div style="font-size: 20px; font-weight: 700; margin-top: 8px;">{invoice.invoice_number}</div>
            </div>
        </div>

        <div class="meta-grid">
            <div>
                <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; font-weight: 700;">Billed To</div>
                <div style="font-size: 16px; font-weight: 600; margin-top: 4px;">{invoice.billing_name}</div>
                <div style="color: #64748b; font-size: 14px;">{invoice.billing_email}</div>
            </div>
            <div style="text-align: right;">
                <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; font-weight: 700;">Invoice Date</div>
                <div style="font-size: 14px; font-weight: 500; margin-top: 4px;">{date_str}</div>
                <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; font-weight: 700; margin-top: 8px;">Payment Date</div>
                <div style="font-size: 14px; font-weight: 500; margin-top: 4px;">{paid_str}</div>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>Item Description</th>
                    <th style="text-align: center;">Qty</th>
                    <th style="text-align: right;">Unit Price</th>
                    <th style="text-align: right;">Amount</th>
                </tr>
            </thead>
            <tbody>
                {rows_html}
            </tbody>
        </table>

        <div class="totals">
            <div class="total-row">
                <span>Subtotal:</span>
                <span>{currency_sym}{invoice.subtotal / 100:.2f}</span>
            </div>
            <div class="total-row">
                <span>Discount:</span>
                <span>-{currency_sym}{invoice.discount_amount / 100:.2f}</span>
            </div>
            <div class="total-row">
                <span>Tax (GST/VAT):</span>
                <span>{currency_sym}{invoice.tax_amount / 100:.2f}</span>
            </div>
            <div class="total-row grand">
                <span>Total Paid:</span>
                <span>{currency_sym}{invoice.amount_paid / 100:.2f}</span>
            </div>
        </div>
    </div>
</body>
</html>"""
