"""
Tests for GET /api/public/sections and GET /api/public/plots/stats (INDL-31 Map/Availability pages).
"""
import pytest
import pytest_asyncio
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession


@pytest_asyncio.fixture
async def section_with_plots(db_session: AsyncSession, test_account):
    from src.apps.sections.models.section import Section
    from src.apps.plots.models.plot import Plot
    from src.apps.plots.models.plot_type import PlotType

    section = Section(
        tenant_id=test_account.id, code="A", name="Heritage Grove",
        description="Mature oak trees", founding_year=1887,
        notable_features="Historic stones",
    )
    db_session.add(section)
    await db_session.flush()

    plot_type = PlotType(tenant_id=test_account.id, name="Single Plot", default_price=4500)
    db_session.add(plot_type)
    await db_session.flush()

    for i in range(3):
        db_session.add(Plot(
            tenant_id=test_account.id, plot_ref=f"A-{i}", section_id=section.id,
            plot_type_id=plot_type.id, status="vacant",
        ))
    db_session.add(Plot(
        tenant_id=test_account.id, plot_ref="A-99", section_id=section.id,
        plot_type_id=plot_type.id, status="occupied",
    ))
    await db_session.flush()
    return section


@pytest.mark.asyncio
async def test_public_sections_empty(client: AsyncClient, test_account):
    response = await client.get(
        "/api/public/sections", headers={"X-Tenant-ID": str(test_account.id)}
    )
    assert response.status_code == 200
    assert response.json()["data"] == []


@pytest.mark.asyncio
async def test_public_sections_with_data(
    client: AsyncClient, section_with_plots, test_account
):
    response = await client.get(
        "/api/public/sections", headers={"X-Tenant-ID": str(test_account.id)}
    )
    assert response.status_code == 200
    data = response.json()["data"]
    assert len(data) == 1
    assert data[0]["code"] == "A"
    assert data[0]["founding_year"] == 1887
    assert data[0]["available_count"] == 3
    assert data[0]["plot_types"] == ["Single Plot"]


@pytest.mark.asyncio
async def test_public_plots_stats(client: AsyncClient, section_with_plots, test_account):
    response = await client.get(
        "/api/public/plots/stats", headers={"X-Tenant-ID": str(test_account.id)}
    )
    assert response.status_code == 200
    data = response.json()["data"]
    assert data["available_count"] == 3
    assert data["min_price"] == 4500.0
    assert data["max_price"] == 4500.0
    assert data["sections_open"] == 1


@pytest.mark.asyncio
async def test_public_sections_no_tenant(client: AsyncClient):
    response = await client.get("/api/public/sections")
    assert response.status_code == 200
    assert response.json()["data"] == []
