"""Tests for settings router (/api/settings)."""
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession

from src.backend.models.orm.setting import SystemSetting
from src.backend.models.orm.user import User
from src.backend.tests.conftest import auth_headers


class TestGetSettings:
    """GET /api/settings/ tests."""

    async def test_get_settings(
        self,
        client: AsyncClient,
        admin_user: User,
        db_session: AsyncSession,
    ):
        """Authenticated user can retrieve settings."""
        # Seed a setting
        setting = SystemSetting(
            setting_key="test_setting",
            setting_value="test_value",
            setting_type="string",
        )
        db_session.add(setting)
        await db_session.flush()

        resp = await client.get(
            "/api/settings/", headers=auth_headers(admin_user)
        )
        assert resp.status_code == 200
        data = resp.json()
        assert isinstance(data, dict)
        assert data.get("test_setting") == "test_value"

    async def test_get_settings_empty(
        self, client: AsyncClient, maker_user: User
    ):
        """Empty settings returns empty dict."""
        resp = await client.get(
            "/api/settings/", headers=auth_headers(maker_user)
        )
        assert resp.status_code == 200
        assert resp.json() == {} or isinstance(resp.json(), dict)

    async def test_get_setting_by_key(
        self,
        client: AsyncClient,
        admin_user: User,
        db_session: AsyncSession,
    ):
        """Settings dict contains specific key after creation."""
        setting = SystemSetting(
            setting_key="csv_delimiter",
            setting_value=";",
            setting_type="string",
        )
        db_session.add(setting)
        await db_session.flush()

        resp = await client.get(
            "/api/settings/", headers=auth_headers(admin_user)
        )
        assert resp.status_code == 200
        assert resp.json()["csv_delimiter"] == ";"


class TestUpdateSettings:
    """PUT /api/settings/ tests."""

    async def test_update_settings(
        self, client: AsyncClient, admin_user: User
    ):
        """Admin can update/create settings."""
        resp = await client.put(
            "/api/settings/",
            headers=auth_headers(admin_user),
            json={
                "company_name": "Tielogic Srl",
                "csv_delimiter": ",",
            },
        )
        assert resp.status_code == 200
        data = resp.json()
        assert data["message"].startswith("Updated")
        assert "company_name" in data["updated_keys"]
        assert "csv_delimiter" in data["updated_keys"]

        # Verify persistence
        get_resp = await client.get(
            "/api/settings/", headers=auth_headers(admin_user)
        )
        settings = get_resp.json()
        assert settings["company_name"] == "Tielogic Srl"

    async def test_settings_require_admin(
        self, client: AsyncClient, maker_user: User
    ):
        """Non-admin user cannot update settings."""
        resp = await client.put(
            "/api/settings/",
            headers=auth_headers(maker_user),
            json={"some_key": "some_value"},
        )
        assert resp.status_code == 403
