import datetime

import pytest

from openinghours.models import OpeningHoursItem, OpeningHoursSet


@pytest.fixture
def opening_hours_set(db):
    return OpeningHoursSet.objects.create(
        name="Vanlige åpningstider",
        effective_from=datetime.date(2025, 1, 1),
    )


def test_opening_hours_set_str_with_end_date():
    ohs = OpeningHoursSet(
        name="Sommer",
        effective_from=datetime.date(2025, 6, 1),
        effective_to=datetime.date(2025, 8, 31),
    )
    assert str(ohs) == "Sommer (2025-06-01 - 2025-08-31)"


def test_opening_hours_set_str_uses_infinity_when_open_ended():
    ohs = OpeningHoursSet(
        name="Forever",
        effective_from=datetime.date(2025, 1, 1),
        effective_to=None,
    )
    assert str(ohs) == "Forever (2025-01-01 - ∞)"


def test_opening_hours_streamfield_week_roundtrip(opening_hours_set):
    OpeningHoursItem.objects.create(
        opening_hours_set=opening_hours_set,
        function="glassbaren",
        week=[
            (
                "week",
                {
                    "monday": {
                        "time_from": datetime.time(15, 0),
                        "time_to": datetime.time(23, 0),
                        "custom": "",
                    },
                    "tuesday": {"time_from": None, "time_to": None, "custom": "Stengt"},
                    "wednesday": {"time_from": None, "time_to": None, "custom": ""},
                    "thursday": {"time_from": None, "time_to": None, "custom": ""},
                    "friday": {"time_from": None, "time_to": None, "custom": ""},
                    "saturday": {"time_from": None, "time_to": None, "custom": ""},
                    "sunday": {"time_from": None, "time_to": None, "custom": ""},
                },
            ),
        ],
    )

    reloaded = OpeningHoursSet.objects.get(pk=opening_hours_set.pk)
    item = reloaded.items.get()
    assert item.function == "glassbaren"

    week_block = item.week[0]
    assert week_block.block_type == "week"
    assert week_block.value["monday"]["time_from"] == datetime.time(15, 0)
    assert week_block.value["monday"]["time_to"] == datetime.time(23, 0)
    assert week_block.value["tuesday"]["custom"] == "Stengt"


def test_graphql_opening_hours_sets_query(db, graphql_post):
    OpeningHoursSet.objects.create(
        name="Sommer 2025",
        effective_from=datetime.date(2025, 6, 1),
        effective_to=datetime.date(2025, 8, 31),
    )

    response, body = graphql_post(
        """
        query {
          openingHoursSets {
            name
            effectiveFrom
            effectiveTo
          }
        }
        """
    )

    assert response.status_code == 200
    assert "errors" not in body, body
    names = [s["name"] for s in body["data"]["openingHoursSets"]]
    assert "Sommer 2025" in names
