from fastapi import HTTPException
from fastapi.testclient import TestClient

from app.models.status import IndexingState, IndexingStatusResponse
from tests.conftest import TRUSTED_HEADERS


def test_indexing_status_returns_workspace_stats(monkeypatch):
    from app.main import app
    from app.services import upload_service as upload_module

    async def _fake_status(repo_id, ctx):
        return IndexingStatusResponse(
            repo_id=repo_id,
            state=IndexingState.READY,
            files_indexed=2,
            chunks_total=7,
            stale_count=1,
            last_indexed_at="2026-07-01T12:00:00",
        )

    monkeypatch.setattr(
        upload_module.upload_service,
        "get_indexing_status",
        _fake_status,
    )

    client = TestClient(app)
    response = client.get(
        "/api/v1/indexing/status",
        headers=TRUSTED_HEADERS,
        params={"repo_id": "lucos:ws:abc123"},
    )

    assert response.status_code == 200
    assert response.json() == {
        "repo_id": "lucos:ws:abc123",
        "state": "ready",
        "files_total": 0,
        "files_indexed": 2,
        "chunks_total": 7,
        "stale_count": 1,
        "last_indexed_at": "2026-07-01T12:00:00",
    }


def test_indexing_status_denies_repo_without_acl(monkeypatch):
    from app.main import app
    from app.services import upload_service as upload_module

    async def _unexpected_status(repo_id, ctx):
        raise AssertionError("status lookup should not run")

    monkeypatch.setattr(
        upload_module.upload_service,
        "get_indexing_status",
        _unexpected_status,
    )

    client = TestClient(app)
    response = client.get(
        "/api/v1/indexing/status",
        headers={**TRUSTED_HEADERS, "X-Repo-Ids": "lucos:ws:allowed"},
        params={"repo_id": "lucos:ws:blocked"},
    )

    assert response.status_code == 403


def test_indexing_status_returns_not_found(monkeypatch):
    from app.main import app
    from app.services import upload_service as upload_module

    async def _fake_status(repo_id, ctx):
        raise HTTPException(
            status_code=404,
            detail={"code": "REPO_NOT_FOUND", "repo_id": repo_id},
        )

    monkeypatch.setattr(
        upload_module.upload_service,
        "get_indexing_status",
        _fake_status,
    )

    client = TestClient(app)
    response = client.get(
        "/api/v1/indexing/status",
        headers=TRUSTED_HEADERS,
        params={"repo_id": "lucos:ws:missing"},
    )

    assert response.status_code == 404
    assert response.json()["detail"]["code"] == "REPO_NOT_FOUND"
