import uuid
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import ForbiddenError, QuotaExceededError
from modules.billing.coupon_service import CouponService
from modules.billing.entitlement_service import EntitlementService
from modules.billing.models import Coupon, Plan
from modules.billing.service import BillingService
from modules.tenants.models import Tenant


@pytest.mark.asyncio
async def test_coupon_validation_and_discounts(db_session: AsyncSession):
    billing_service = BillingService(db_session)
    await billing_service.seed_default_plans()

    coupon_service = CouponService(db_session)

    # 1. Percentage discount coupon
    code_pct = f"SAVE20_{uuid.uuid4().hex[:4].upper()}"
    pct_coupon = Coupon(
        id=uuid.uuid4(),
        code=code_pct,
        discount_type="percentage",
        discount_value=20,  # 20%
        currency="INR",
        min_order_amount=50000,
        is_active=True,
    )
    await coupon_service.repo.create_coupon(pct_coupon)

    is_valid, c, discount, msg = await coupon_service.validate_coupon(code_pct, "starter", 99900)
    assert is_valid is True
    assert discount == int(99900 * 0.20)  # 19980

    # 2. Fixed amount discount coupon
    code_fixed = f"FLAT500_{uuid.uuid4().hex[:4].upper()}"
    fixed_coupon = Coupon(
        id=uuid.uuid4(),
        code=code_fixed,
        discount_type="fixed_amount",
        discount_value=50000,  # ₹500
        currency="INR",
        min_order_amount=50000,
        is_active=True,
    )
    await coupon_service.repo.create_coupon(fixed_coupon)

    is_valid, c, discount, msg = await coupon_service.validate_coupon(code_fixed, "starter", 99900)
    assert is_valid is True
    assert discount == 50000

    # 3. Expired coupon must fail
    code_exp = f"EXPIRED_{uuid.uuid4().hex[:4].upper()}"
    expired_coupon = Coupon(
        id=uuid.uuid4(),
        code=code_exp,
        discount_type="fixed_amount",
        discount_value=10000,
        currency="INR",
        expires_at=datetime.now(timezone.utc) - timedelta(days=1),
        is_active=True,
    )
    await coupon_service.repo.create_coupon(expired_coupon)

    is_valid, c, discount, msg = await coupon_service.validate_coupon(code_exp, "starter", 99900)
    assert is_valid is False
    assert "expired" in msg.lower()

    # 4. Max redemptions reached must fail
    code_max = f"ONETIME_{uuid.uuid4().hex[:4].upper()}"
    maxed_coupon = Coupon(
        id=uuid.uuid4(),
        code=code_max,
        discount_type="fixed_amount",
        discount_value=10000,
        currency="INR",
        max_redemptions=1,
        times_redeemed=1,
        is_active=True,
    )
    await coupon_service.repo.create_coupon(maxed_coupon)

    is_valid, c, discount, msg = await coupon_service.validate_coupon(code_max, "starter", 99900)
    assert is_valid is False
    assert "maximum redemptions" in msg.lower()


@pytest.mark.asyncio
async def test_entitlement_enforcement_and_feature_gates(db_session: AsyncSession):
    tenant_id = uuid.uuid4()
    billing_service = BillingService(db_session)
    await billing_service.seed_default_plans()

    # Create Tenant
    tenant = Tenant(
        id=tenant_id,
        name=f"Entitlement Org {tenant_id.hex[:6]}",
        slug=f"ent-org-{tenant_id.hex[:6]}",
        plan_id="free",
    )
    db_session.add(tenant)
    await db_session.commit()

    entitlement_service = EntitlementService(db_session)

    # Free tier has max_bots=1, ai_enabled=False
    limits = await entitlement_service.get_tenant_limits_and_usage(tenant_id)
    assert limits["plan_id"] == "free"
    assert limits["bots"]["limit"] == 1
    assert limits["features"]["ai_enabled"] is False

    # Accessing AI on free tier must raise ForbiddenError
    with pytest.raises(ForbiddenError):
        await entitlement_service.check_feature_access(tenant_id, "ai_enabled")
