import re

import pytest
import pytest_mock
from temporalio.testing import ActivityEnvironment

from csirtmu.beta_temporal.config import Config as WorkerConfig
from csirtmu.beta_temporal.external_services.rt import structs
from csirtmu.beta_temporal.external_services.rt.client import RTClient
from csirtmu.beta_temporal.workflows.set_spam_category_on_spam_header import SpamCategoryOnHeaderActivities


class TestActionsOnSpam:
    async def test_actions_on_spam_ticket_obj_is_none(
        self,
        worker_config: WorkerConfig,
        mock_transaction_obj: structs.TransactionStruct,
        test_activity_env: ActivityEnvironment,
    ) -> None:
        activities = SpamCategoryOnHeaderActivities(RTClient(worker_config.rt))
        mock_transaction_obj.ticket_obj = None
        with pytest.raises(ValueError, match=re.escape("Ticket object is None.")):
            await test_activity_env.run(activities.actions_on_spam, mock_transaction_obj)

    async def test_actions_on_spam_category_already_set(
        self,
        worker_config: WorkerConfig,
        mock_transaction_obj: structs.TransactionStruct,
        mocker: pytest_mock.MockerFixture,
        test_activity_env: ActivityEnvironment,
    ) -> None:
        assert mock_transaction_obj.ticket_obj is not None
        activities = SpamCategoryOnHeaderActivities(RTClient(worker_config.rt))
        mock_transaction_obj.ticket_obj.custom_fields = [structs.CustomFieldStruct("", "", "", "Category", ["idk"])]
        edit_ticket_mock = mocker.patch(
            "csirtmu.beta_temporal.workflows.set_spam_category_on_spam_header.RTClient.edit_ticket",
        )
        edit_ticket_mock.return_value = None
        await test_activity_env.run(activities.actions_on_spam, mock_transaction_obj)
        edit_ticket_mock.assert_not_called()

    async def test_actions_on_spam_success(
        self,
        worker_config: WorkerConfig,
        mock_transaction_obj: structs.TransactionStruct,
        mocker: pytest_mock.MockerFixture,
        test_activity_env: ActivityEnvironment,
    ) -> None:
        assert mock_transaction_obj.ticket_obj is not None
        activities = SpamCategoryOnHeaderActivities(RTClient(worker_config.rt))
        edit_ticket_mock = mocker.patch(
            "csirtmu.beta_temporal.workflows.set_spam_category_on_spam_header.RTClient.edit_ticket",
        )
        edit_ticket_mock.return_value = None
        await test_activity_env.run(activities.actions_on_spam, mock_transaction_obj)
        edit_ticket_mock.assert_called_once_with(mock_transaction_obj.ticket_obj.id, CustomFields={"Category": "Spam"})
