from __future__ import annotations

from types import SimpleNamespace

import pytest
from fastapi import HTTPException

from app.api.v1.endpoints import bootstrap as bootstrap_endpoint
from app.schemas.bootstrap import BootstrapSetupPayload


def completed_settings() -> SimpleNamespace:
    return SimpleNamespace(
        setup_completed=True,
        company_name="X-Financial",
        company_code="XF-001",
        admin_email="admin@example.com",
        web_host="0.0.0.0",
        web_port=5273,
        app_host="0.0.0.0",
        app_port=8000,
        postgres_host="postgres.internal",
        postgres_port=5432,
        postgres_db="x_financial",
        postgres_user="postgres-admin",
        postgres_password="secret",
        redis_url="redis://redis.internal:6379/0",
    )


def setup_payload() -> BootstrapSetupPayload:
    return BootstrapSetupPayload(
        company_name="X-Financial",
        company_code="XF-001",
        admin_email="admin@example.com",
        postgres_host="postgres.internal",
        postgres_port=5432,
        postgres_db="x_financial",
        postgres_user="postgres-admin",
        postgres_password="secret",
        redis_url="redis://redis.internal:6379/0",
    )


def test_completed_bootstrap_state_redacts_infrastructure(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(bootstrap_endpoint, "get_settings", completed_settings)

    state = bootstrap_endpoint.get_bootstrap_state()

    assert state.initialized is True
    assert state.database.host == ""
    assert state.database.username == ""
    assert state.database.password_configured is True
    assert state.redis.url == ""


def test_completed_bootstrap_rejects_anonymous_reconfiguration(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(bootstrap_endpoint, "get_settings", completed_settings)

    with pytest.raises(HTTPException) as exc_info:
        bootstrap_endpoint.initialize_bootstrap(setup_payload(), None)

    assert exc_info.value.status_code == 403
