import uuid
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import NotFoundError, ValidationError
from modules.billing.models import Coupon, CouponRedemption, Referral
from modules.billing.repository import BillingRepository


class CouponService:
    """Manages discount coupons and referral rewards."""

    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = BillingRepository(db)

    async def validate_coupon(
        self,
        code: str,
        plan_id: str,
        order_amount: int,
    ) -> tuple[bool, Optional[Coupon], int, str]:
        """
        Validates coupon against plan, order value, expiry date, and redemption limits.
        Returns: (is_valid, coupon, discount_amount, message)
        """
        coupon = await self.repo.get_coupon_by_code(code)
        if not coupon:
            return False, None, 0, f"Coupon code '{code}' does not exist"

        if not coupon.is_active:
            return False, coupon, 0, f"Coupon '{code}' is no longer active"

        now = datetime.now(timezone.utc)
        if coupon.expires_at and now > coupon.expires_at:
            return False, coupon, 0, f"Coupon '{code}' has expired"

        if coupon.max_redemptions and coupon.times_redeemed >= coupon.max_redemptions:
            return False, coupon, 0, f"Coupon '{code}' has reached its maximum redemptions limit"

        if coupon.applicable_plans and plan_id not in coupon.applicable_plans:
            return False, coupon, 0, f"Coupon '{code}' is not applicable to the '{plan_id}' plan"

        if order_amount < coupon.min_order_amount:
            return False, coupon, 0, f"Minimum order amount of {coupon.min_order_amount / 100:.2f} required for coupon"

        # Calculate discount
        if coupon.discount_type == "percentage":
            discount = int(order_amount * (coupon.discount_value / 100))
        else:  # fixed_amount
            discount = min(coupon.discount_value, order_amount)

        if coupon.max_discount_amount:
            discount = min(discount, coupon.max_discount_amount)

        return True, coupon, discount, "Coupon applied successfully"

    async def record_redemption(
        self,
        tenant_id: uuid.UUID,
        coupon_id: uuid.UUID,
        order_id: uuid.UUID,
        discount_applied: int,
    ) -> CouponRedemption:
        return await self.repo.record_coupon_redemption(
            tenant_id=tenant_id,
            coupon_id=coupon_id,
            order_id=order_id,
            discount_applied=discount_applied,
        )

    async def register_referral(
        self,
        referrer_tenant_id: uuid.UUID,
        referred_tenant_id: uuid.UUID,
        referral_code: str,
    ) -> Referral:
        existing = await self.repo.get_referral_by_referred_tenant(referred_tenant_id)
        if existing:
            return existing
        return await self.repo.create_referral(
            referrer_tenant_id=referrer_tenant_id,
            referred_tenant_id=referred_tenant_id,
            referral_code=referral_code,
        )
