from __future__ import annotations

from datetime import datetime, timedelta

import pytest

from blackout_notifier.models import TEHRAN, Outage, OutageDataError, jalali_query_window


def test_jalali_query_window_uses_tehran_date() -> None:
    utc_near_midnight = datetime.fromisoformat("2026-07-16T20:31:00+00:00")

    assert jalali_query_window(utc_near_midnight, 5) == ("1405/04/26", "1405/04/31")


def test_outage_parses_api_payload() -> None:
    outage = Outage.from_api(
        {
            "outage_number": 404992999001,
            "outage_date": "1405/04/27",
            "outage_start_time": "09:00",
            "outage_stop_time": "11:00",
            "outage_address": " فیدر آزمایشی ",
            "reason_outage": "مدیریت بار",
            "is_planned": True,
        }
    )

    assert outage.outage_number == "404992999001"
    assert outage.address == "فیدر آزمایشی"
    assert outage.start_datetime() == datetime(2026, 7, 18, 9, 0, tzinfo=TEHRAN)


def test_outage_supports_cross_midnight_window() -> None:
    outage = Outage(
        outage_number="1",
        outage_date="1405/04/27",
        start_time="23:00",
        stop_time="01:00",
        address="",
        reason="",
        is_planned=True,
    )

    assert outage.stop_datetime() - outage.start_datetime() == timedelta(hours=2)


def test_outage_rejects_invalid_date() -> None:
    with pytest.raises(OutageDataError, match="invalid Jalali"):
        Outage.from_api(
            {
                "outage_number": "1",
                "outage_date": "not-a-date",
                "outage_start_time": "09:00",
                "outage_stop_time": "11:00",
            }
        )
