import uuid
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from modules.bots.models import Bot, BotUser
from modules.tenants.models import Tenant


@pytest.mark.asyncio
async def test_broadcast_and_notifications_full_lifecycle(
    async_client: AsyncClient,
    db_session: AsyncSession,
):
    # 1. Register User and Create Tenant
    email = f"bcast_user_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp = await async_client.post(
        "/api/v1/auth/register",
        json={"email": email, "password": "Password123!", "full_name": "Broadcast Admin"},
    )
    assert reg_resp.status_code == 201
    token = reg_resp.json()["data"]["access_token"]
    headers = {"Authorization": f"Bearer {token}"}

    tenant_resp = await async_client.post(
        "/api/v1/tenants",
        headers=headers,
        json={"name": "Broadcast Media Corp", "slug": f"bcast-{uuid.uuid4().hex[:6]}"},
    )
    assert tenant_resp.status_code == 201
    tenant_id = tenant_resp.json()["data"]["id"]
    headers["X-Tenant-ID"] = tenant_id
    tenant_uuid = uuid.UUID(tenant_id)

    # 2. Setup Bot and Bot Users in DB
    bot_id = uuid.uuid4()
    bot = Bot(
        id=bot_id,
        tenant_id=tenant_uuid,
        name="Flash Sale Announcer",
        username=f"sale_announcer_{uuid.uuid4().hex[:6]}",
        status="active",
        default_locale="en",
    )
    db_session.add(bot)
    await db_session.flush()

    # Create 4 users:
    # u1: en, active -> should receive campaign
    # u2: hi, active -> excluded by locale filter
    # u3: en, blocked -> strictly excluded
    # u4: en, opted out -> strictly excluded
    u1 = BotUser(
        id=uuid.uuid4(),
        bot_id=bot_id,
        telegram_user_id=200001,
        preferred_locale="en",
        is_blocked=False,
        is_opted_out=False,
    )
    u2 = BotUser(
        id=uuid.uuid4(),
        bot_id=bot_id,
        telegram_user_id=200002,
        preferred_locale="hi",
        is_blocked=False,
        is_opted_out=False,
    )
    u3 = BotUser(
        id=uuid.uuid4(),
        bot_id=bot_id,
        telegram_user_id=200003,
        preferred_locale="en",
        is_blocked=True,
        is_opted_out=False,
    )
    u4 = BotUser(
        id=uuid.uuid4(),
        bot_id=bot_id,
        telegram_user_id=200004,
        preferred_locale="en",
        is_blocked=False,
        is_opted_out=True,
    )
    db_session.add_all([u1, u2, u3, u4])
    await db_session.commit()

    # 3. Create Broadcast Campaign
    camp_payload = {
        "bot_id": str(bot_id),
        "title": "Spring Flash Sale 2026",
        "message_text": "🔥 <b>Exclusive Offer:</b> Get 50% off with promo code <code>SPRING50</code>!",
        "target_filter": {"locale": "en"},
        "inline_keyboard": [
            [{"text": "Claim Discount 🎁", "url": "https://example.com/deal"}]
        ],
        "media_type": "none",
        "rate_limit_per_second": 25,
    }
    create_camp_resp = await async_client.post("/api/v1/broadcasts", headers=headers, json=camp_payload)
    assert create_camp_resp.status_code == 201
    camp_data = create_camp_resp.json()["data"]
    campaign_id = camp_data["id"]
    assert camp_data["status"] == "draft"
    assert camp_data["title"] == "Spring Flash Sale 2026"
    assert camp_data["rate_limit_per_second"] == 25

    # 4. List Campaigns
    list_camps_resp = await async_client.get("/api/v1/broadcasts", headers=headers)
    assert list_camps_resp.status_code == 200
    assert len(list_camps_resp.json()["data"]) >= 1

    # 5. Get Campaign Details
    get_camp_resp = await async_client.get(f"/api/v1/broadcasts/{campaign_id}", headers=headers)
    assert get_camp_resp.status_code == 200
    assert get_camp_resp.json()["data"]["id"] == campaign_id

    # 6. Update Campaign while in draft
    update_camp_resp = await async_client.patch(
        f"/api/v1/broadcasts/{campaign_id}",
        headers=headers,
        json={"title": "Spring Flash Sale 2026 - Extended Edition"},
    )
    assert update_camp_resp.status_code == 200
    assert update_camp_resp.json()["data"]["title"] == "Spring Flash Sale 2026 - Extended Edition"

    # 7. Dispatch Campaign & Verify Delivery
    dispatch_resp = await async_client.post(f"/api/v1/broadcasts/{campaign_id}/dispatch", headers=headers)
    assert dispatch_resp.status_code == 200
    disp_data = dispatch_resp.json()["data"]
    # Exactly 1 recipient eligible (User 1; User 2 filtered by locale, User 3 blocked, User 4 opted out)
    assert disp_data["total_recipients"] == 1
    assert disp_data["delivered_count"] == 1
    assert disp_data["failed_count"] == 0
    assert disp_data["status"] == "completed"

    # 8. Check Campaign Delivery Stats
    stats_resp = await async_client.get(f"/api/v1/broadcasts/{campaign_id}/stats", headers=headers)
    assert stats_resp.status_code == 200
    stats = stats_resp.json()["data"]
    assert stats["total_recipients"] == 1
    assert stats["delivered_count"] == 1
    assert stats["failed_count"] == 0
    assert stats["delivery_rate_pct"] == 100.0

    # 9. User Opt-Out Workflow (/stop or /optout handling)
    opt_out_resp = await async_client.post(
        "/api/v1/broadcasts/opt-out",
        headers=headers,
        json={
            "bot_id": str(bot_id),
            "telegram_user_id": 200001,
            "opt_out": True,
        },
    )
    assert opt_out_resp.status_code == 200

    # Create new campaign for same bot targeting locale "en"
    second_camp_resp = await async_client.post(
        "/api/v1/broadcasts",
        headers=headers,
        json={
            "bot_id": str(bot_id),
            "title": "Second Announcement",
            "message_text": "Hello again!",
            "target_filter": {"locale": "en"},
        },
    )
    assert second_camp_resp.status_code == 201
    second_camp_id = second_camp_resp.json()["data"]["id"]

    dispatch_second_resp = await async_client.post(
        f"/api/v1/broadcasts/{second_camp_id}/dispatch",
        headers=headers,
    )
    assert dispatch_second_resp.status_code == 200
    # Now user 1 is also opted out, so 0 eligible recipients
    assert dispatch_second_resp.json()["data"]["total_recipients"] == 0
    assert dispatch_second_resp.json()["data"]["status"] == "completed"

    # 10. In-App Notifications Engine Integration
    # Create notification alert
    create_notif_resp = await async_client.post(
        "/api/v1/notifications",
        headers=headers,
        json={
            "title": "Campaign Broadcast Complete",
            "message": "Your broadcast campaign 'Spring Flash Sale' has completed successfully.",
            "type": "broadcast",
            "priority": "normal",
        },
    )
    assert create_notif_resp.status_code == 201
    notif_data = create_notif_resp.json()["data"]
    notif_id = notif_data["id"]
    assert notif_data["is_read"] is False

    # Check unread counter badge
    count_resp = await async_client.get("/api/v1/notifications/unread-count", headers=headers)
    assert count_resp.status_code == 200
    assert count_resp.json()["data"]["unread_count"] >= 1

    # List notifications
    list_notifs_resp = await async_client.get("/api/v1/notifications?unread_only=true", headers=headers)
    assert list_notifs_resp.status_code == 200
    assert any(n["id"] == notif_id for n in list_notifs_resp.json()["data"])

    # Mark as read
    mark_read_resp = await async_client.post(
        "/api/v1/notifications/mark-read",
        headers=headers,
        json={"notification_ids": [notif_id]},
    )
    assert mark_read_resp.status_code == 200
    assert mark_read_resp.json()["data"]["updated_count"] >= 1

    # Verify unread count is 0
    count_after_resp = await async_client.get("/api/v1/notifications/unread-count", headers=headers)
    assert count_after_resp.status_code == 200
    assert count_after_resp.json()["data"]["unread_count"] == 0
