"""GET /home/summary — the Studio's built-in Home dashboard (app/routers/
home.py): admins get every section, other internal users only the sections
their roles grant "view" on, and Public Portal accounts none at all."""

import uuid

from app.core.auth import create_access_token
from tests.conftest import AsyncSessionLocal
from app.models.identity import Role, User, UserRole


async def _token(tenant_id: uuid.UUID, action_matrix: dict[str, list[str]], *, vendor: bool = False) -> dict[str, str]:
    unique = uuid.uuid4().hex[:8]
    async with AsyncSessionLocal() as db:
        async with db.begin():
            role = Role(tenant_id=tenant_id, name=f"Pytest Role {unique}", is_system_role=False, action_matrix=action_matrix)
            db.add(role)
            user = User(tenant_id=tenant_id, name=f"Pytest User {unique}", email=f"pytest-{unique}@example.com", status="active")
            db.add(user)
            await db.flush()
            db.add(UserRole(user_id=user.id, role_id=role.id))
            user_id = user.id
    token = create_access_token(tenant_id=tenant_id, user_id=user_id, vendor_id=uuid.uuid4() if vendor else None)
    return {"Authorization": f"Bearer {token}"}


async def test_admin_sees_every_section_with_submission_counts(client, auth_headers):
    form = (
        await client.post("/forms", headers=auth_headers, json={"name": "Home Intake", "field_definitions": [{"name": "a", "type": "text", "label": "A"}]})
    ).json()
    assert (await client.post(f"/forms/{form['form_id']}/publish", headers=auth_headers)).status_code == 200
    for _ in range(2):
        r = await client.post("/form-submissions", headers=auth_headers, json={"form_id": form["form_id"], "form_version": 1, "field_values": {"a": "x"}})
        assert r.status_code == 201, r.text

    resp = await client.get("/home/summary", headers=auth_headers, params={"tz": "Asia/Kolkata"})
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["is_admin"] is True and body["tenant_name"]

    subs = body["submissions"]
    assert subs["total"] == 2 and subs["last_7d"] == 2
    assert len(subs["daily"]) == 14 and subs["daily"][-1]["count"] == 2
    assert subs["top_forms"] == [{"form_id": form["form_id"], "name": "Home Intake", "count": 2}]
    assert subs["recent"][0]["form_name"] == "Home Intake"

    assert body["build"]["forms"] == {"published": 1, "draft": 0}
    for section in ("workflows", "people", "activity", "dashboards"):
        assert body[section] is not None, section
    assert body["people"]["internal_users"] >= 1


async def test_limited_user_only_gets_granted_sections(client, test_tenant):
    headers = await _token(test_tenant["tenant_id"], {"forms": ["view"]})
    body = (await client.get("/home/summary", headers=headers)).json()
    assert body["is_admin"] is False
    assert body["submissions"] is not None and body["build"]["forms"] is not None
    assert body["workflows"] is None and body["people"] is None and body["activity"] is None and body["dashboards"] is None
    assert body["build"]["pages"] is None and body["build"]["datasources"] is None
    # Personal sections are always there.
    assert body["notifications"]["unread"] >= 0 and body["my_work"]["in_progress"] == 0


async def test_portal_users_and_bad_time_zones_are_rejected(client, test_tenant, auth_headers):
    vendor = await _token(test_tenant["tenant_id"], {}, vendor=True)
    assert (await client.get("/home/summary", headers=vendor)).status_code == 403
    assert (await client.get("/home/summary", headers=auth_headers, params={"tz": "Mars/Base"})).status_code == 422
