"""Jira service unit tests (FASE-1.2)."""

from datetime import datetime
from unittest.mock import MagicMock, patch
from uuid import uuid4

import pytest

from app.domain.exceptions import InvalidOperationError
from app.models.jira_link import JiraLink, JiraLinkEntityType
from app.services import jira_service


def test_get_jira_client_raises_when_disabled(monkeypatch):
    monkeypatch.setattr("app.services.jira_service.settings.JIRA_ENABLED", False)
    jira_service._jira_client = None
    with pytest.raises(InvalidOperationError, match="not enabled"):
        jira_service.get_jira_client()


@patch("app.services.jira_service.get_jira_client")
def test_sync_aegis_to_jira_adds_comment(mock_get_client, db):
    mock_jira = MagicMock()
    mock_get_client.return_value = mock_jira

    link = JiraLink(
        entity_type=JiraLinkEntityType.test,
        entity_id=uuid4(),
        jira_issue_key="SEC-99",
    )
    jira_service.sync_aegis_to_jira(db, link, {"state": "validated", "result": "pass"})

    mock_jira.issue_add_comment.assert_called_once()
    args = mock_jira.issue_add_comment.call_args[0]
    assert args[0] == "SEC-99"
    assert "Aegis Sync Update" in args[1]
    assert link.last_synced_at is not None


@patch("app.services.jira_service.get_jira_client")
def test_search_jira_issues_maps_fields(mock_get_client):
    mock_jira = MagicMock()
    mock_get_client.return_value = mock_jira
    mock_jira.jql.return_value = {
        "issues": [
            {
                "key": "TST-1",
                "fields": {
                    "summary": "Test issue",
                    "status": {"name": "In Progress"},
                    "assignee": {"displayName": "Alice"},
                    "priority": {"name": "High"},
                },
            }
        ]
    }

    results = jira_service.search_jira_issues("project = TEST", max_results=5)

    assert len(results) == 1
    assert results[0]["issue_key"] == "TST-1"
    assert results[0]["summary"] == "Test issue"
    assert results[0]["status"] == "In Progress"
    mock_jira.jql.assert_called_once()
