"""Tests for merge_pr.py.

Mocks api_request and credentials.
"""
import sys
import unittest
from unittest.mock import patch

sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent))
import merge_pr  # noqa: E402


FAKE_CREDS = "Basic dGVzdHVzZXI6dGVzdHBhc3M="


class TestArgParsing(unittest.TestCase):

    def test_missing_pr_number_exits(self):
        with self.assertRaises(SystemExit):
            merge_pr.main([])


class TestMergeDisabled(unittest.TestCase):
    """Direct CLI merge is disabled (#16) — fails closed, no API call."""

    @patch("merge_pr.api_request")
    @patch("merge_pr.get_auth_header", return_value=FAKE_CREDS)
    def test_merge_fails_closed_without_api_call(self, _auth, mock_api):
        rc = merge_pr.main(["--pr-number", "81"])
        self.assertEqual(rc, 2)
        mock_api.assert_not_called()

    @patch("merge_pr.api_request")
    @patch("merge_pr.get_auth_header", return_value=FAKE_CREDS)
    def test_no_merge_even_with_force_and_method(self, _auth, mock_api):
        rc = merge_pr.main([
            "--pr-number", "81",
            "--do", "squash",
            "--title", "Squash title",
            "--message", "Squash message",
            "--force",
            "--remote", "prgs",
        ])
        self.assertEqual(rc, 2)
        mock_api.assert_not_called()

    def test_message_points_to_gated_workflow(self):
        from _pytest.monkeypatch import MonkeyPatch
        import io
        with patch("merge_pr.get_auth_header", return_value=FAKE_CREDS), \
                patch("merge_pr.api_request") as mock_api:
            buf = io.StringIO()
            monkeypatch = MonkeyPatch()
            monkeypatch.setattr(sys, "stderr", buf)
            try:
                rc = merge_pr.main(["--pr-number", "81"])
            finally:
                monkeypatch.undo()
        self.assertEqual(rc, 2)
        mock_api.assert_not_called()
        msg = buf.getvalue().lower()
        self.assertIn("disabled", msg)
        self.assertIn("gitea_merge_pr", msg)


if __name__ == "__main__":
    unittest.main()
