import uuid
import pytest
from httpx import AsyncClient
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from infrastructure.telegram.service import TelegramApiService
from infrastructure.telegram.webhook import hash_webhook_secret
from modules.bots.models import BotWebhook, BotUser
from modules.identity.models import User


@pytest.mark.asyncio
async def test_multi_tenant_multi_bot_engine_lifecycle(
    async_client: AsyncClient,
    db_session: AsyncSession,
):
    # -------------------------------------------------------------
    # 1. Setup Mock Bot Tokens
    # -------------------------------------------------------------
    token_a1 = f"token_a1_{uuid.uuid4().hex[:8]}_test"
    token_a2 = f"token_a2_{uuid.uuid4().hex[:8]}_test"
    token_b1 = f"token_b1_{uuid.uuid4().hex[:8]}_test"

    bot_uname_a1 = f"alpha_bot_1_{uuid.uuid4().hex[:6]}"
    bot_uname_a2 = f"alpha_bot_2_{uuid.uuid4().hex[:6]}"
    bot_uname_b1 = f"beta_bot_1_{uuid.uuid4().hex[:6]}"

    TelegramApiService.register_mock_bot(token_a1, bot_uname_a1, "Alpha One")
    TelegramApiService.register_mock_bot(token_a2, bot_uname_a2, "Alpha Two")
    TelegramApiService.register_mock_bot(token_b1, bot_uname_b1, "Beta One")

    # -------------------------------------------------------------
    # 2. Register User A & Tenant Alpha
    # -------------------------------------------------------------
    user_a_email = f"user_a_{uuid.uuid4().hex[:6]}@example.com"
    resp_a = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_a_email, "password": "PasswordA123!", "full_name": "Alice Alpha"},
    )
    token_user_a = resp_a.json()["data"]["access_token"]

    tenant_a_resp = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {token_user_a}"},
        json={"name": "Tenant Alpha Org", "slug": f"alpha-{uuid.uuid4().hex[:6]}"},
    )
    tenant_a_id = tenant_a_resp.json()["data"]["id"]
    headers_a = {
        "Authorization": f"Bearer {token_user_a}",
        "X-Tenant-ID": str(tenant_a_id),
    }

    # Set Tenant Alpha to Pro plan to support multiple bots under entitlement limits
    from datetime import datetime, timedelta, timezone
    from modules.billing.service import BillingService
    from modules.tenants.models import Tenant
    b_serv = BillingService(db_session)
    await b_serv.seed_default_plans()
    now_dt = datetime.now(timezone.utc)
    await b_serv.repo.create_subscription(
        tenant_id=uuid.UUID(tenant_a_id),
        plan_id="pro",
        status="active",
        current_period_start=now_dt,
        current_period_end=now_dt + timedelta(days=30),
    )
    t_obj = await db_session.get(Tenant, uuid.UUID(tenant_a_id))
    if t_obj:
        t_obj.plan_id = "pro"
        await db_session.commit()

    # -------------------------------------------------------------
    # 3. Register User B & Tenant Beta
    # -------------------------------------------------------------
    user_b_email = f"user_b_{uuid.uuid4().hex[:6]}@example.com"
    resp_b = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_b_email, "password": "PasswordB123!", "full_name": "Bob Beta"},
    )
    token_user_b = resp_b.json()["data"]["access_token"]

    tenant_b_resp = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {token_user_b}"},
        json={"name": "Tenant Beta Org", "slug": f"beta-{uuid.uuid4().hex[:6]}"},
    )
    tenant_b_id = tenant_b_resp.json()["data"]["id"]
    headers_b = {
        "Authorization": f"Bearer {token_user_b}",
        "X-Tenant-ID": str(tenant_b_id),
    }

    # -------------------------------------------------------------
    # 4. Tenant Alpha Registers Bot A1 and Bot A2
    # -------------------------------------------------------------
    reg_a1 = await async_client.post(
        "/api/v1/bots",
        headers=headers_a,
        json={"token": token_a1, "name": "Alpha Bot 1", "default_locale": "en"},
    )
    assert reg_a1.status_code == 201, reg_a1.text
    bot_a1_data = reg_a1.json()["data"]
    bot_a1_id = bot_a1_data["id"]
    assert bot_a1_data["username"] == bot_uname_a1
    assert bot_a1_data["webhook_active"] is True
    # Ensure raw token was NEVER returned
    assert "token" not in bot_a1_data
    assert "encrypted_token" not in bot_a1_data

    reg_a2 = await async_client.post(
        "/api/v1/bots",
        headers=headers_a,
        json={"token": token_a2, "name": "Alpha Bot 2", "default_locale": "hi"},
    )
    assert reg_a2.status_code == 201
    bot_a2_id = reg_a2.json()["data"]["id"]

    # -------------------------------------------------------------
    # 5. Tenant Beta Registers Bot B1
    # -------------------------------------------------------------
    reg_b1 = await async_client.post(
        "/api/v1/bots",
        headers=headers_b,
        json={"token": token_b1, "name": "Beta Bot 1", "default_locale": "en"},
    )
    assert reg_b1.status_code == 201
    bot_b1_id = reg_b1.json()["data"]["id"]

    # Duplicate registration of same username must fail
    reg_dup = await async_client.post(
        "/api/v1/bots",
        headers=headers_b,
        json={"token": token_a1, "name": "Duplicate Bot"},
    )
    assert reg_dup.status_code == 409

    # -------------------------------------------------------------
    # 6. Verify Tenant-Scoped Bot Listings
    # -------------------------------------------------------------
    list_a = await async_client.get("/api/v1/bots", headers=headers_a)
    assert list_a.status_code == 200
    bots_for_a = [b["id"] for b in list_a.json()["data"]]
    assert len(bots_for_a) == 2
    assert bot_a1_id in bots_for_a
    assert bot_a2_id in bots_for_a
    assert bot_b1_id not in bots_for_a  # Tenant Alpha CANNOT see Tenant Beta's bot!

    list_b = await async_client.get("/api/v1/bots", headers=headers_b)
    assert list_b.status_code == 200
    bots_for_b = [b["id"] for b in list_b.json()["data"]]
    assert len(bots_for_b) == 1
    assert bot_b1_id in bots_for_b
    assert bot_a1_id not in bots_for_b  # Tenant Beta CANNOT see Tenant Alpha's bots!

    # -------------------------------------------------------------
    # 7. Cross-Tenant Unauthorized Attack Verification
    # -------------------------------------------------------------
    # User B tries to view Bot A1 -> Must be 404 (not in workspace)
    cross_view = await async_client.get(f"/api/v1/bots/{bot_a1_id}", headers=headers_b)
    assert cross_view.status_code == 404

    # User B tries to update Bot A1
    cross_patch = await async_client.patch(
        f"/api/v1/bots/{bot_a1_id}",
        headers=headers_b,
        json={"name": "Hacked Name"},
    )
    assert cross_patch.status_code == 404

    # User B tries to deactivate Bot A1
    cross_deact = await async_client.post(f"/api/v1/bots/{bot_a1_id}/deactivate", headers=headers_b)
    assert cross_deact.status_code == 404

    # User B tries to delete Bot A1
    cross_del = await async_client.delete(f"/api/v1/bots/{bot_a1_id}", headers=headers_b)
    assert cross_del.status_code == 404

    # -------------------------------------------------------------
    # 8. Superadmin Platform-Wide Oversight
    # -------------------------------------------------------------
    # Normal user cannot access superadmin route
    unauth_admin = await async_client.get("/api/v1/admin/bots", headers=headers_a)
    assert unauth_admin.status_code == 403

    # Promote User A to superuser in DB
    user_record = await db_session.execute(select(User).where(User.email == user_a_email))
    u = user_record.scalar_one()
    u.is_superuser = True
    await db_session.commit()

    # Superadmin can view all platform bots across all tenants
    admin_bots_resp = await async_client.get("/api/v1/admin/bots", headers=headers_a)
    assert admin_bots_resp.status_code == 200
    all_platform_bot_ids = [b["id"] for b in admin_bots_resp.json()["data"]]
    assert bot_a1_id in all_platform_bot_ids
    assert bot_a2_id in all_platform_bot_ids
    assert bot_b1_id in all_platform_bot_ids

    # -------------------------------------------------------------
    # 9. Webhook Ingestion, Secret Verification & Deduplication
    # -------------------------------------------------------------
    # Set a known secret token for testing
    test_secret = "super_secure_webhook_secret_token_2026"
    test_secret_hash = hash_webhook_secret(test_secret)

    webhook_record = await db_session.execute(
        select(BotWebhook).where(BotWebhook.bot_id == uuid.UUID(bot_a1_id))
    )
    wh = webhook_record.scalar_one()
    wh.secret_hash = test_secret_hash
    await db_session.commit()

    webhook_url = f"/webhooks/telegram/{bot_a1_id}"

    # 9a. Request with invalid secret -> 401 Unauthorized
    bad_wh_resp = await async_client.post(
        webhook_url,
        headers={"X-Telegram-Bot-Api-Secret-Token": "invalid_wrong_secret"},
        json={"update_id": 999},
    )
    assert bad_wh_resp.status_code == 401

    # 9b. Request with missing secret header -> 401 Unauthorized
    missing_wh_resp = await async_client.post(webhook_url, json={"update_id": 999})
    assert missing_wh_resp.status_code == 401

    # 9c. Valid Webhook update: User /start message
    update_payload = {
        "update_id": 5001,
        "message": {
            "message_id": 100,
            "from": {
                "id": 998877,
                "first_name": "Rohan",
                "last_name": "Sharma",
                "username": "rohan_sharma",
                "language_code": "hi",
            },
            "chat": {"id": 998877},
            "text": "/start",
        },
    }

    wh_ok_resp = await async_client.post(
        webhook_url,
        headers={"X-Telegram-Bot-Api-Secret-Token": test_secret},
        json=update_payload,
    )
    assert wh_ok_resp.status_code == 200
    assert wh_ok_resp.json().get("processed") is True

    # Verify bot user was upserted in DB
    bu_res = await db_session.execute(
        select(BotUser).where(BotUser.bot_id == uuid.UUID(bot_a1_id), BotUser.telegram_user_id == 998877)
    )
    bu = bu_res.scalar_one_or_none()
    assert bu is not None
    assert bu.first_name == "Rohan"
    assert bu.username == "rohan_sharma"

    # 9d. Update Deduplication: Same update_id sent again must be dropped as duplicate
    wh_dup_resp = await async_client.post(
        webhook_url,
        headers={"X-Telegram-Bot-Api-Secret-Token": test_secret},
        json=update_payload,
    )
    assert wh_dup_resp.status_code == 200
    assert wh_dup_resp.json().get("duplicate") is True

    # -------------------------------------------------------------
    # 10. Bot Deactivation and Reactivation
    # -------------------------------------------------------------
    # Deactivate Bot A1
    deact_resp = await async_client.post(f"/api/v1/bots/{bot_a1_id}/deactivate", headers=headers_a)
    assert deact_resp.status_code == 200
    assert deact_resp.json()["data"]["status"] == "inactive"

    # Inactive bot webhook fails
    inactive_wh = await async_client.post(
        webhook_url,
        headers={"X-Telegram-Bot-Api-Secret-Token": test_secret},
        json={"update_id": 5002, "message": {"chat": {"id": 123}, "text": "hello"}},
    )
    assert inactive_wh.status_code == 404

    # Reactivate Bot A1
    act_resp = await async_client.post(f"/api/v1/bots/{bot_a1_id}/activate", headers=headers_a)
    assert act_resp.status_code == 200
    assert act_resp.json()["data"]["status"] == "active"

    # -------------------------------------------------------------
    # 11. Bot Deletion Lifecycle
    # -------------------------------------------------------------
    del_resp = await async_client.delete(f"/api/v1/bots/{bot_a2_id}", headers=headers_a)
    assert del_resp.status_code == 200

    # Bot A2 is deleted
    list_after_del = await async_client.get("/api/v1/bots", headers=headers_a)
    remaining_bots = [b["id"] for b in list_after_del.json()["data"]]
    assert bot_a2_id not in remaining_bots
    assert bot_a1_id in remaining_bots
