from pathlib import Path

from fastapi.testclient import TestClient

from app.main import app


def test_health() -> None:
    with TestClient(app) as client:
        response = client.get("/health")
        assert response.status_code == 200
        assert response.json() == {"status": "ok"}


def test_process_success_and_download(fixtures: dict[str, Path]) -> None:
    with TestClient(app) as client:
        with fixtures["table_a_success"].open("rb") as table_a, fixtures["template_b"].open("rb") as template_b:
            response = client.post(
                "/process",
                files={
                    "table_a": ("table_a.xlsx", table_a, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
                    "template_b": ("template_b.xlsx", template_b, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
                },
            )
        payload = response.json()
        assert response.status_code == 200
        assert payload["success"] is True
        download = client.get(payload["download_url"])
        assert download.status_code == 200
        assert download.headers["content-type"].startswith("application/vnd.openxmlformats")
        assert download.content[:2] == b"PK"


def test_process_missing_address(fixtures: dict[str, Path]) -> None:
    with TestClient(app) as client:
        with fixtures["table_a_missing_address"].open("rb") as table_a, fixtures["template_b"].open("rb") as template_b:
            response = client.post(
                "/process",
                files={
                    "table_a": ("table_a.xlsx", table_a, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
                    "template_b": ("template_b.xlsx", template_b, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
                },
            )
        payload = response.json()
        assert response.status_code == 200
        assert payload["success"] is False
        assert "download_url" not in payload
        assert payload["issues"]
