"""Tests for auth.resolve_credentials_path."""

from __future__ import annotations

from pathlib import Path

import pytest

from gsc.auth import ENV_VAR, AuthError, resolve_credentials_path


def test_raises_when_no_source(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv(ENV_VAR, raising=False)
    with pytest.raises(AuthError, match=ENV_VAR):
        resolve_credentials_path(None)


def test_accepts_cli_flag(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv(ENV_VAR, raising=False)
    fake = tmp_path / "creds.json"
    fake.write_text("{}", encoding="utf-8")
    assert resolve_credentials_path(str(fake)) == fake


def test_accepts_env_var(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    fake = tmp_path / "env-creds.json"
    fake.write_text("{}", encoding="utf-8")
    monkeypatch.setenv(ENV_VAR, str(fake))
    assert resolve_credentials_path(None) == fake


def test_cli_flag_overrides_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    env_file = tmp_path / "env.json"
    env_file.write_text("{}", encoding="utf-8")
    cli_file = tmp_path / "cli.json"
    cli_file.write_text("{}", encoding="utf-8")
    monkeypatch.setenv(ENV_VAR, str(env_file))
    assert resolve_credentials_path(str(cli_file)) == cli_file


def test_cli_flag_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv(ENV_VAR, raising=False)
    missing = tmp_path / "nope.json"
    with pytest.raises(AuthError, match="does not exist"):
        resolve_credentials_path(str(missing))
