"""Jira sync scheduled job tests (FASE-1.7)."""

from unittest.mock import patch
from uuid import uuid4

import pytest

from app.jobs.jira_sync_job import sync_all_jira_links
from app.models.jira_link import JiraLink, JiraLinkEntityType
from tests.conftest import TestingSessionLocal


@pytest.fixture(autouse=True)
def _job_uses_test_db(monkeypatch):
    """Route the job's SessionLocal to the in-memory SQLite test engine."""
    import app.database as database_module

    monkeypatch.setattr(database_module, "_SessionLocal", TestingSessionLocal)
    monkeypatch.setattr(
        "app.jobs.jira_sync_job.SessionLocal",
        TestingSessionLocal,
    )


def test_sync_all_jira_links_skips_when_disabled(monkeypatch, db):
    monkeypatch.setattr("app.jobs.jira_sync_job.settings.JIRA_ENABLED", False)
    with patch("app.jobs.jira_sync_job.jira_service.sync_jira_to_aegis") as mock_sync:
        sync_all_jira_links()
        mock_sync.assert_not_called()


@patch("app.jobs.jira_sync_job.jira_service.sync_jira_to_aegis")
def test_sync_all_jira_links_updates_links(mock_sync, monkeypatch, db, admin_user):
    monkeypatch.setattr("app.jobs.jira_sync_job.settings.JIRA_ENABLED", True)

    link = JiraLink(
        entity_type=JiraLinkEntityType.test,
        entity_id=uuid4(),
        jira_issue_key="SEC-1",
        created_by=admin_user.id,
    )
    db.add(link)
    db.commit()

    sync_all_jira_links()

    assert mock_sync.call_count == 1


@patch("app.jobs.jira_sync_job.jira_service.sync_jira_to_aegis")
def test_sync_all_jira_links_continues_on_single_failure(mock_sync, monkeypatch, db, admin_user):
    monkeypatch.setattr("app.jobs.jira_sync_job.settings.JIRA_ENABLED", True)

    for key in ("SEC-A", "SEC-B"):
        db.add(
            JiraLink(
                entity_type=JiraLinkEntityType.test,
                entity_id=uuid4(),
                jira_issue_key=key,
                created_by=admin_user.id,
            ),
        )
    db.commit()

    mock_sync.side_effect = [Exception("issue deleted"), None]

    sync_all_jira_links()

    assert mock_sync.call_count == 2
