"""verify_admin 보안 강화 회귀 테스트 (CODE_REVIEW F2).

운영 .env에서 ADMIN_API_KEY가 누락되면 /api/trade/balance, /api/trade/order
인증이 무력화되는 버그를 막기 위한 가드.
"""
import os
from unittest.mock import patch

import pytest
from fastapi import HTTPException

from app import main as stock_main


def test_verify_admin_rejects_when_key_missing_and_no_dev_flag(monkeypatch):
    """ADMIN_API_KEY 미설정 + ALLOW_UNAUTHENTICATED_ADMIN 미설정 → 503."""
    monkeypatch.setattr(stock_main, "ADMIN_API_KEY", "")
    monkeypatch.delenv("ALLOW_UNAUTHENTICATED_ADMIN", raising=False)
    with pytest.raises(HTTPException) as exc_info:
        stock_main.verify_admin(x_admin_key=None)
    assert exc_info.value.status_code == 503
    assert "ADMIN_API_KEY" in exc_info.value.detail


def test_verify_admin_allows_when_key_missing_with_dev_flag(monkeypatch):
    """ADMIN_API_KEY 미설정 + ALLOW_UNAUTHENTICATED_ADMIN=true → 통과 (개발 모드)."""
    monkeypatch.setattr(stock_main, "ADMIN_API_KEY", "")
    monkeypatch.setenv("ALLOW_UNAUTHENTICATED_ADMIN", "true")
    stock_main.verify_admin(x_admin_key=None)  # 예외 없으면 통과


def test_verify_admin_rejects_wrong_key(monkeypatch):
    """ADMIN_API_KEY 설정 + 잘못된 키 → 401 (regression)."""
    monkeypatch.setattr(stock_main, "ADMIN_API_KEY", "secret123")
    with pytest.raises(HTTPException) as exc_info:
        stock_main.verify_admin(x_admin_key="wrong")
    assert exc_info.value.status_code == 401


def test_verify_admin_allows_correct_key(monkeypatch):
    """ADMIN_API_KEY 설정 + 올바른 키 → 통과 (regression)."""
    monkeypatch.setattr(stock_main, "ADMIN_API_KEY", "secret123")
    stock_main.verify_admin(x_admin_key="secret123")  # 예외 없으면 통과
