"""Tests for prodigy_teams.auth — FileSecrets and AuthStateImpl basics."""

from __future__ import annotations

from pathlib import Path

import pytest

from prodigy_teams.auth import FileSecrets
from prodigy_teams.errors import ProdigyTeamsParseSecretsError


class TestFileSecrets:
    def test_load_missing_file_returns_empty(self, tmp_path: Path):
        s = FileSecrets.load(tmp_path / "nonexistent.json")
        assert s.id_token is None
        assert s.api_token is None
        assert s.broker_tokens == {}

    def test_save_and_load_roundtrip(self, tmp_path: Path):
        path = tmp_path / "secrets.json"
        s = FileSecrets(id_token="test-token")
        s.save(path)
        loaded = FileSecrets.load(path)
        assert loaded.id_token == "test-token"

    def test_save_creates_parent_dirs(self, tmp_path: Path):
        path = tmp_path / "a" / "b" / "secrets.json"
        s = FileSecrets()
        s.save(path)
        assert path.exists()

    def test_save_sets_file_permissions(self, tmp_path: Path):
        import os
        import stat

        path = tmp_path / "secrets.json"
        s = FileSecrets()
        s.save(path)
        mode = stat.S_IMODE(os.stat(path).st_mode)
        assert mode == 0o600

    def test_load_invalid_json_raises(self, tmp_path: Path):
        path = tmp_path / "secrets.json"
        path.write_text("not valid json")
        with pytest.raises(ProdigyTeamsParseSecretsError):
            FileSecrets.load(path)

    def test_load_invalid_api_token_raises(self, tmp_path: Path):
        path = tmp_path / "secrets.json"
        path.write_text('{"api_token": {"access_token": ""}}')
        with pytest.raises(ProdigyTeamsParseSecretsError):
            FileSecrets.load(path)

    def test_clean_removes_file(self, tmp_path: Path):
        path = tmp_path / "secrets.json"
        path.write_text("{}")
        FileSecrets.clean(path)
        assert not path.exists()

    def test_clean_missing_file_no_error(self, tmp_path: Path):
        path = tmp_path / "nonexistent.json"
        FileSecrets.clean(path)  # Should not raise
