"""
GET /api/v1/news/export — the "Published At" / "Created At" CSV columns
must show a plain date, not a full timestamp with microseconds and a
UTC offset (e.g. "2026-07-09T05:13:40.830033+00:00").
"""
import csv
import io

import pytest
import pytest_asyncio
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession

from src.apps.news.models.news_post import NewsPost

pytestmark = pytest.mark.asyncio

EXPORT_URL = "/api/v1/news/export"


@pytest_asyncio.fixture(autouse=True)
async def _plan_gate_news(test_account, db_session: AsyncSession):
    """INDL-59: the News router (this whole file) is gated behind
    require_feature("news") — Starter lacks it. The shared `test_account`
    fixture (tests/conftest.py) defaults to Starter; bump it to
    Professional here, scoped to this file only."""
    test_account.plan = "professional"
    await db_session.flush()


def _headers(token: str, tenant_id) -> dict:
    return {"Authorization": f"Bearer {token}", "X-Tenant-ID": str(tenant_id)}


async def _make_post(db: AsyncSession, tenant_id) -> NewsPost:
    post = NewsPost(
        tenant_id=tenant_id,
        title="Plot on discount",
        category="Heritage",
        excerpt="10% discount this week",
        status="published",
    )
    db.add(post)
    await db.flush()
    return post


@pytest.mark.asyncio
async def test_export_created_at_and_published_at_are_date_only(
    client: AsyncClient, db_session: AsyncSession, admin_token: str, test_account,
):
    post = await _make_post(db_session, test_account.id)
    post.published_at = post.created_at
    await db_session.flush()

    resp = await client.get(EXPORT_URL, headers=_headers(admin_token, test_account.id))
    assert resp.status_code == 200, resp.text

    rows = list(csv.reader(io.StringIO(resp.text)))
    header, data_rows = rows[0], rows[1:]
    row = next(r for r in data_rows if r[header.index("ID")] == str(post.id))

    created_at = row[header.index("Created At")]
    published_at = row[header.index("Published At")]

    assert len(created_at) == 10 and created_at.count("-") == 2, created_at
    assert len(published_at) == 10 and published_at.count("-") == 2, published_at
    assert "T" not in created_at and "T" not in published_at
    assert created_at == post.created_at.date().isoformat()
    assert published_at == post.published_at.date().isoformat()


@pytest.mark.asyncio
async def test_export_published_at_blank_when_unpublished(
    client: AsyncClient, db_session: AsyncSession, admin_token: str, test_account,
):
    post = await _make_post(db_session, test_account.id)
    post.status = "draft"
    post.published_at = None
    await db_session.flush()

    resp = await client.get(EXPORT_URL, headers=_headers(admin_token, test_account.id))
    assert resp.status_code == 200, resp.text

    rows = list(csv.reader(io.StringIO(resp.text)))
    header, data_rows = rows[0], rows[1:]
    row = next(r for r in data_rows if r[header.index("ID")] == str(post.id))
    assert row[header.index("Published At")] == ""
