from types import SimpleNamespace
from unittest.mock import Mock, patch

from django.test import SimpleTestCase

from jaystools import tasks


class TestSyncTasks(SimpleTestCase):
    def test_sync_user_runs_steps_in_order(self):
        user = Mock()
        user.profile.main_character = SimpleNamespace(character_id=9000001, character_name="Pilot One")

        with patch("jaystools.tasks.User.objects.select_related") as mock_select_related:
            mock_select_related.return_value.get.return_value = user

            call_order = []
            with patch("jaystools.tasks._sync_character_from_esi", side_effect=lambda _: call_order.append("esi")):
                with patch("jaystools.tasks._sync_autogroups_for_user", side_effect=lambda _: call_order.append("autogroups")):
                    with patch("jaystools.tasks._sync_discord_for_user", side_effect=lambda _: call_order.append("discord")):
                        result = tasks.sync_user_esi_and_discord(user_pk=12, triggered_by_user_pk=34)

        self.assertEqual(call_order, ["esi", "autogroups", "discord"])
        self.assertEqual(result["user_pk"], 12)
        self.assertEqual(result["triggered_by_user_pk"], 34)
        self.assertEqual(result["main_character_id"], 9000001)

    def test_sync_user_raises_when_main_character_missing(self):
        user = Mock()
        user.profile.main_character = None

        with patch("jaystools.tasks.User.objects.select_related") as mock_select_related:
            mock_select_related.return_value.get.return_value = user
            with self.assertRaises(ValueError):
                tasks.sync_user_esi_and_discord(user_pk=12)


