#!/usr/bin/python3
"""Tests for slpkg/gpg_verify.py using pytest."""

from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest
from slpkg.gpg_verify import GPGVerify


@pytest.fixture
def mock_config():
    """Mock config_load for GPGVerify."""
    with patch("slpkg.gpg_verify.config_load") as mock:
        mock.gpg_verification = True
        mock.red = ""
        mock.endc = ""
        yield mock


@pytest.fixture
def gpg_verify_inst(mock_config):
    """Fixture to create a GPGVerify instance."""
    with patch("slpkg.gpg_verify.View"), \
         patch("slpkg.gpg_verify.ViewProcess"):
        inst = GPGVerify()
        return inst


def test_verify_disabled(gpg_verify_inst):
    """Test verify when GPG verification is disabled."""
    gpg_verify_inst.gpg_verification = False
    with patch("subprocess.run") as mock_run:
        gpg_verify_inst.verify([Path("test.asc")])
        assert not mock_run.called


def test_verify_success(gpg_verify_inst):
    """Test successful GPG verification."""
    mock_proc = MagicMock()
    mock_proc.returncode = 0
    
    with patch("subprocess.run", return_value=mock_proc) as mock_run:
        gpg_verify_inst.verify([Path("test.asc")])
        mock_run.assert_called_once()
        gpg_verify_inst.view_process.done.assert_called_once()


def test_verify_failure(gpg_verify_inst):
    """Test GPG verification failure."""
    mock_proc = MagicMock()
    mock_proc.returncode = 1
    
    with patch("subprocess.run", return_value=mock_proc):
        gpg_verify_inst.verify([Path("test.asc")])
        gpg_verify_inst.view_process.failed.assert_called_once()
        # Should prompt user
        gpg_verify_inst.view.question.assert_called_once()


def test_verify_multiple_files(gpg_verify_inst):
    """Test verifying multiple files, one failing."""
    mock_proc_ok = MagicMock()
    mock_proc_ok.returncode = 0
    mock_proc_fail = MagicMock()
    mock_proc_fail.returncode = 1
    
    with patch("subprocess.run", side_effect=[mock_proc_ok, mock_proc_fail]):
        gpg_verify_inst.verify([Path("ok.asc"), Path("fail.asc")])
        gpg_verify_inst.view_process.failed.assert_called_once()
        gpg_verify_inst.view.question.assert_called_once()
