import datetime

import pytest
import pytest_mock
from freezegun import freeze_time
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_due_on_ticket_status_change import SetDueOnTicketStatusChangeActivities


class TestSetDue:
    async def test_set_due_ticket_obj_is_none(
        self,
        worker_config: WorkerConfig,
        test_activity_env: ActivityEnvironment,
        mock_transaction_obj: structs.TransactionStruct,
    ) -> None:
        activities = SetDueOnTicketStatusChangeActivities(RTClient(worker_config.rt))
        mock_transaction_obj.ticket_obj = None
        assert (await test_activity_env.run(activities.set_due, 2, mock_transaction_obj)) is None

    @pytest.mark.parametrize(("days", "today"), [(i, j) for i in range(7) for j in range(7) if i + j < 11])
    async def test_set_due(
        self,
        days: int,
        today: int,
        worker_config: WorkerConfig,
        test_activity_env: ActivityEnvironment,
        mock_transaction_obj: structs.TransactionStruct,
        mocker: pytest_mock.MockerFixture,
    ) -> None:
        assert mock_transaction_obj.ticket_obj is not None
        activities = SetDueOnTicketStatusChangeActivities(RTClient(worker_config.rt))
        edit_ticket_mock = mocker.patch(
            "csirtmu.beta_temporal.workflows.set_due_on_ticket_status_change.RTClient.edit_ticket",
        )
        edit_ticket_mock.return_value = None
        now = datetime.datetime(2025, 2, 17 + today, 11, 22, 1, tzinfo=datetime.UTC)
        with freeze_time(now):
            await test_activity_env.run(activities.set_due, days, mock_transaction_obj)
        weekday = now.weekday()
        if weekday + days > 4:
            days += 1 if weekday == 6 else 2
        due = now + datetime.timedelta(days=days)
        if weekday == 5 or weekday == 6:
            due = due.replace(hour=0, minute=0, second=0)
        edit_ticket_mock.assert_called_once_with(
            mock_transaction_obj.ticket_obj.id,
            Due=due.strftime("%Y-%m-%d %H:%M:%S"),
        )
