"""Tests for authentication, token resolution, and config persistence."""

from __future__ import annotations

from pathlib import Path
from unittest.mock import patch

import pytest

from appliku._auth import _read_config_token, resolve_token, save_token


class TestResolveToken:
    def test_explicit_token_takes_priority(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv("APPLIKU_TOKEN", "env-token")
        assert resolve_token("explicit-token") == "explicit-token"

    def test_env_var_fallback(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv("APPLIKU_TOKEN", "env-token")
        assert resolve_token() == "env-token"

    def test_config_file_fallback(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
        monkeypatch.delenv("APPLIKU_TOKEN", raising=False)
        config = tmp_path / "config.toml"
        config.write_text('[auth]\ntoken = "file-token"\n')

        with patch("appliku._auth.CONFIG_PATH", config):
            assert resolve_token() == "file-token"

    def test_returns_none_when_no_token(
        self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
    ) -> None:
        monkeypatch.delenv("APPLIKU_TOKEN", raising=False)
        config = tmp_path / "nonexistent.toml"

        with patch("appliku._auth.CONFIG_PATH", config):
            assert resolve_token() is None


class TestSaveToken:
    def test_save_creates_file(self, tmp_path: Path) -> None:
        config = tmp_path / "config.toml"
        with patch("appliku._auth.CONFIG_PATH", config):
            save_token("my-token")
        assert config.exists()

    def test_save_and_read_roundtrip(self, tmp_path: Path) -> None:
        config = tmp_path / "config.toml"
        with patch("appliku._auth.CONFIG_PATH", config):
            save_token("roundtrip-token")
            assert _read_config_token() == "roundtrip-token"

    def test_save_creates_parent_dirs(self, tmp_path: Path) -> None:
        config = tmp_path / "nested" / "dir" / "config.toml"
        with patch("appliku._auth.CONFIG_PATH", config):
            save_token("nested-token")
        assert config.exists()


class TestReadConfigToken:
    def test_missing_file_returns_none(self, tmp_path: Path) -> None:
        config = tmp_path / "missing.toml"
        with patch("appliku._auth.CONFIG_PATH", config):
            assert _read_config_token() is None

    def test_malformed_toml_returns_none(self, tmp_path: Path) -> None:
        config = tmp_path / "bad.toml"
        config.write_text("this is not valid toml {{{{")
        with patch("appliku._auth.CONFIG_PATH", config):
            assert _read_config_token() is None

    def test_missing_auth_section_returns_none(self, tmp_path: Path) -> None:
        config = tmp_path / "config.toml"
        config.write_text("[other]\nfoo = 'bar'\n")
        with patch("appliku._auth.CONFIG_PATH", config):
            assert _read_config_token() is None
