"""Attendance & Access Control tests — Phase 9.5."""
from __future__ import annotations

import pytest

from app.events.types import SportsCenterEventType
from app.tests.conftest import TENANT_A, tenant_headers


async def _seed(client, headers):
    center = await client.post(
        "/api/v1/sports-centers",
        json={"code": "att95", "name": "Attendance Center", "status": "active"},
        headers=headers,
    )
    assert center.status_code == 201
    center_id = center.json()["id"]
    mtype = await client.post(
        "/api/v1/membership-types",
        json={"sports_center_id": center_id, "code": "std", "name": "Standard"},
        headers=headers,
    )
    member = await client.post(
        "/api/v1/members",
        json={"sports_center_id": center_id, "display_name": "Att Member", "status": "active"},
        headers=headers,
    )
    membership = await client.post(
        "/api/v1/memberships",
        json={
            "sports_center_id": center_id,
            "membership_type_id": mtype.json()["id"],
            "display_name": "Att Member",
            "member_id": member.json()["id"],
        },
        headers=headers,
    )
    activate = await client.post(
        f"/api/v1/memberships/{membership.json()['id']}/activate",
        headers=headers,
    )
    assert activate.status_code == 200
    return center_id, member.json()["id"], membership.json()["id"]


@pytest.mark.asyncio
async def test_check_in_out(client):
    headers = tenant_headers(TENANT_A)
    center_id, member_id, membership_id = await _seed(client, headers)

    check_in = await client.post(
        "/api/v1/check-in",
        json={
            "sports_center_id": center_id,
            "member_id": member_id,
            "membership_id": membership_id,
        },
        headers=headers,
    )
    assert check_in.status_code == 201, check_in.text

    check_out = await client.post(
        "/api/v1/check-out",
        json={
            "sports_center_id": center_id,
            "member_id": member_id,
            "membership_id": membership_id,
        },
        headers=headers,
    )
    assert check_out.status_code == 201, check_out.text

    history = await client.get(
        f"/api/v1/attendance-records?member_id={member_id}",
        headers=headers,
    )
    assert history.status_code == 200
    assert len(history.json()) >= 2
