import hashlib
import hmac
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from core.config import get_settings
from modules.billing.models import Coupon, Plan, Subscription
from modules.billing.service import BillingService
from modules.tenants.models import Tenant


@pytest.mark.asyncio
async def test_full_billing_lifecycle_and_security(async_client: AsyncClient, db_session: AsyncSession):
    settings = get_settings()

    # 1. Register new user
    email = f"billing_user_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp = await async_client.post(
        "/api/v1/auth/register",
        json={"email": email, "password": "Password123!", "full_name": "Billing Admin"},
    )
    assert reg_resp.status_code == 201
    token = reg_resp.json()["data"]["access_token"]
    headers = {"Authorization": f"Bearer {token}"}

    # Create Tenant for user
    slug = f"billing-tenant-{uuid.uuid4().hex[:6]}"
    create_t_resp = await async_client.post(
        "/api/v1/tenants",
        headers=headers,
        json={"name": "Billing Tenant Corp", "slug": slug},
    )
    assert create_t_resp.status_code == 201
    tenant_id = create_t_resp.json()["data"]["id"]
    headers["X-Tenant-ID"] = tenant_id

    # 2. List available plans
    plans_resp = await async_client.get("/api/v1/billing/plans")
    assert plans_resp.status_code == 200
    plans = plans_resp.json()["data"]
    assert len(plans) >= 4
    plan_ids = [p["id"] for p in plans]
    assert "free" in plan_ids
    assert "starter" in plan_ids
    assert "pro" in plan_ids
    assert "enterprise" in plan_ids

    # 3. Verify initial subscription is Free
    sub_resp = await async_client.get("/api/v1/billing/subscription", headers=headers)
    assert sub_resp.status_code == 200
    assert sub_resp.json()["data"]["plan_id"] == "free"

    # 4. Create coupon for discount verification
    b_service = BillingService(db_session)
    coupon_code = f"LAUNCH_{uuid.uuid4().hex[:4].upper()}"
    coupon = Coupon(
        id=uuid.uuid4(),
        code=coupon_code,
        discount_type="fixed_amount",
        discount_value=50000,  # ₹500
        min_order_amount=50000,
        is_active=True,
    )
    await b_service.coupons.repo.create_coupon(coupon)

    # 5. Create checkout order for Starter plan with coupon
    checkout_resp = await async_client.post(
        "/api/v1/billing/checkout",
        headers=headers,
        json={
            "plan_id": "starter",
            "provider": "razorpay",
            "coupon_code": coupon_code,
        },
    )
    assert checkout_resp.status_code == 201
    order_data = checkout_resp.json()["data"]
    order_id = order_data["order_id"]
    # Starter is ₹999 - ₹500 coupon = ₹499 (49900 paise)
    assert order_data["amount"] == 49900
    assert order_data["status"] == "created"
    gateway_order_id = order_data["gateway_order_id"]
    assert gateway_order_id is not None

    # 6. Server-Side Verification Security Check: Tampered/Fake signature must fail
    fake_verify_resp = await async_client.post(
        "/api/v1/billing/checkout/verify",
        headers=headers,
        json={
            "order_id": order_id,
            "payment_id": "pay_fake_attacker_123",
            "signature": "forged_invalid_signature_hex",
            "provider": "razorpay",
        },
    )
    assert fake_verify_resp.status_code == 400
    assert "Cryptographic payment signature verification failed" in fake_verify_resp.json()["message"]

    # 7. Valid cryptographic signature verification must succeed
    payment_id = f"pay_{uuid.uuid4().hex[:14]}"
    key_secret = settings.RAZORPAY_KEY_SECRET or "rzp_secret_placeholder"
    valid_sig = hmac.new(
        key_secret.encode("utf-8"),
        f"{gateway_order_id}|{payment_id}".encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()

    verify_resp = await async_client.post(
        "/api/v1/billing/checkout/verify",
        headers=headers,
        json={
            "order_id": order_id,
            "payment_id": payment_id,
            "signature": valid_sig,
            "provider": "razorpay",
        },
    )
    assert verify_resp.status_code == 200
    v_data = verify_resp.json()["data"]
    assert v_data["success"] is True
    assert v_data["status"] == "paid"
    invoice_id = v_data["invoice_id"]
    assert invoice_id is not None

    # 8. Subscription must now be active on Starter plan
    sub_after = await async_client.get("/api/v1/billing/subscription", headers=headers)
    assert sub_after.json()["data"]["plan_id"] == "starter"
    assert sub_after.json()["data"]["status"] == "active"

    # 9. Verify invoice generation & printable HTML endpoint
    invoices_resp = await async_client.get("/api/v1/billing/invoices", headers=headers)
    assert invoices_resp.status_code == 200
    assert len(invoices_resp.json()["data"]) >= 1

    html_resp = await async_client.get(f"/api/v1/billing/invoices/{invoice_id}/html", headers=headers)
    assert html_resp.status_code == 200
    assert "text/html" in html_resp.headers["content-type"]
    assert "Telegram SaaS Platform" in html_resp.text
    assert "Invoice" in html_resp.text

    # 10. Test Wallet: credit wallet balance and pay subscription
    wallet_resp = await async_client.get("/api/v1/billing/wallet", headers=headers)
    assert wallet_resp.status_code == 200
    assert wallet_resp.json()["data"]["balance"] == 0

    # Credit wallet with ₹5,000 credits
    await b_service.wallets.credit(
        tenant_id=uuid.UUID(tenant_id),
        amount=500000,
        reference_type="topup",
        description="Manual credit top-up",
    )

    wallet_after_credit = await async_client.get("/api/v1/billing/wallet", headers=headers)
    assert wallet_after_credit.json()["data"]["balance"] == 500000

    # Pay for Pro plan directly with wallet credits
    wallet_pay_resp = await async_client.post(
        "/api/v1/billing/wallet/pay",
        headers=headers,
        json={"plan_id": "pro"},
    )
    assert wallet_pay_resp.status_code == 200
    assert wallet_pay_resp.json()["data"]["status"] == "paid"

    # Verify subscription is now Pro
    sub_pro = await async_client.get("/api/v1/billing/subscription", headers=headers)
    assert sub_pro.json()["data"]["plan_id"] == "pro"

    # Verify wallet balance debited
    wallet_after_pay = await async_client.get("/api/v1/billing/wallet", headers=headers)
    assert wallet_after_pay.json()["data"]["balance"] == 500000 - 299900  # 200100 left

    # 11. Test Refund Handling
    refund_resp = await async_client.post(
        "/api/v1/billing/refunds",
        headers=headers,
        json={
            "order_id": order_id,
            "amount": 49900,
            "reason": "Customer requested full refund within satisfaction guarantee",
        },
    )
    assert refund_resp.status_code == 200
    ref_data = refund_resp.json()["data"]
    assert ref_data["status"] == "processed"
    assert ref_data["amount"] == 49900

    # 12. Cancellation (Period end)
    cancel_resp = await async_client.post(
        "/api/v1/billing/subscription/cancel",
        headers=headers,
        json={"immediate": False},
    )
    assert cancel_resp.status_code == 200
    assert cancel_resp.json()["data"]["cancel_at_period_end"] is True

    # 13. Expiry and Grace period transition test
    sub = await b_service.repo.get_tenant_subscription(uuid.UUID(tenant_id))
    # Simulate past period end
    past_end = datetime.now(timezone.utc) - timedelta(hours=1)
    await b_service.repo.update_subscription(sub, current_period_end=past_end)

    # Trigger expiry check
    grace_sub = await b_service.process_subscription_expiry(uuid.UUID(tenant_id))
    assert grace_sub.status == "grace_period"
    assert grace_sub.grace_period_ends_at is not None

    # Simulate past grace period
    past_grace = datetime.now(timezone.utc) - timedelta(days=4)
    await b_service.repo.update_subscription(sub, grace_period_ends_at=past_grace)
    expired_sub = await b_service.process_subscription_expiry(uuid.UUID(tenant_id))
    assert expired_sub.status == "expired"
    assert expired_sub.plan_id == "free"
