# Standard Library
from datetime import datetime, timezone as dt_timezone
from unittest.mock import Mock

# Django
from django.test import SimpleTestCase

from incursions.everef import _apply_state_update, _parse_filename_timestamp
from incursions.models.incursion import Incursion


class TestEveRefHelpers(SimpleTestCase):
    def test_parse_filename_timestamp_returns_utc_datetime(self) -> None:
        result = _parse_filename_timestamp("incursions-2026-03-25_12-34-56.json.bz2")

        self.assertEqual(
            result,
            datetime(2026, 3, 25, 12, 34, 56, tzinfo=dt_timezone.utc),
        )

    def test_parse_filename_timestamp_returns_none_for_invalid_name(self) -> None:
        self.assertIsNone(_parse_filename_timestamp("not-an-incursion-file.json"))

    def test_apply_state_update_sets_mobilizing_timestamp_and_normalizes_boss(self) -> None:
        timestamp = datetime(2026, 3, 25, 12, 0, tzinfo=dt_timezone.utc)
        incursion = Mock(
            mobilizing_timestamp=None,
            withdrawing_timestamp=None,
            state="established",
            has_boss="true",
        )

        _apply_state_update(incursion, "mobilizing", timestamp)

        self.assertEqual(incursion.mobilizing_timestamp, timestamp)
        self.assertEqual(incursion.state, "mobilizing")
        self.assertTrue(incursion.has_boss)
        incursion.save.assert_called_once_with()

    def test_apply_state_update_does_not_overwrite_ended_state(self) -> None:
        timestamp = datetime(2026, 3, 25, 12, 0, tzinfo=dt_timezone.utc)
        incursion = Mock(
            mobilizing_timestamp=None,
            withdrawing_timestamp=None,
            state=Incursion.States.ENDED,
            has_boss=False,
        )

        _apply_state_update(incursion, "withdrawing", timestamp)

        self.assertEqual(incursion.withdrawing_timestamp, timestamp)
        self.assertEqual(incursion.state, Incursion.States.ENDED)
        incursion.save.assert_called_once_with()
