from __future__ import annotations

import asyncio

import pytest

pytest.importorskip("fastapi")

from starlette.testclient import TestClient

from aicd.api_serve import create_chat_read_api
from aicd.db.store import TaskStore
from aicd.home import init_home


def test_chat_read_api_messages_and_auth(tmp_path) -> None:
    h = tmp_path / "home"
    _, layout, _ = init_home(h)

    async def seed() -> None:
        store = TaskStore(layout["db"])
        conn = await store.connect()
        await store.append_chat_message(
            conn, session_id="s1", role="user", content="hello"
        )
        await conn.close()

    asyncio.run(seed())

    app = create_chat_read_api(db_path=layout["db"], api_key=None)
    with TestClient(app) as client:
        assert client.get("/health").json() == {"ok": True}
        r = client.get("/v1/sessions/s1/messages")
        assert r.status_code == 200
        body = r.json()
        assert body["total"] == 1
        assert body["messages"][0]["content"] == "hello"

    app2 = create_chat_read_api(db_path=layout["db"], api_key="secret")
    with TestClient(app2) as client:
        assert client.get("/v1/sessions/s1/messages").status_code == 401
        r2 = client.get(
            "/v1/sessions/s1/messages",
            headers={"X-API-Key": "secret"},
        )
        assert r2.status_code == 200
