from __future__ import annotations

from datetime import datetime, timedelta, timezone
from pathlib import Path

import pytest

from gateway.platforms.telegram_customer_bootstrap import (
    BootstrapError,
    BootstrapState,
    CustomerDraft,
    RoomBootstrapStore,
)


def _draft() -> CustomerDraft:
    return CustomerDraft(
        customer_key="pilot_001",
        display_name="Pilot Customer",
        starts_on="2026-08-21",
        daily_time="08:00",
        weekly_weekday=0,
        monthly_day=1,
        calories_kcal=2200,
        protein_g=140,
        meals=("breakfast", "lunch", "dinner"),
    )


def test_unclaimed_invite_expires_at_24_hour_boundary(tmp_path: Path) -> None:
    issued_at = datetime(2026, 8, 21, tzinfo=timezone.utc)
    current_time = [issued_at]
    store = RoomBootstrapStore(
        tmp_path / "bootstrap",
        now=lambda: current_time[0],
    )
    prepared = store.prepare_rehearsal_customer_invite(
        _draft(),
        bot_username="dualcoachtestbot",
        owner_id="12",
    )
    token = prepared.customer_link.rsplit("=", 1)[1]

    assert prepared.expires_at == issued_at + timedelta(hours=24)
    current_time[0] = issued_at + timedelta(hours=23, minutes=59, seconds=59)
    assert store.rehearsal_customer_invite_session(token) == prepared.session

    current_time[0] = issued_at + timedelta(hours=24)
    with pytest.raises(BootstrapError, match="unavailable"):
        _ = store.rehearsal_customer_invite_session(token)
    assert store.get(prepared.session.session_id).state is BootstrapState.EXPIRED


def test_invite_claimed_before_24_hours_remains_single_use(tmp_path: Path) -> None:
    issued_at = datetime(2026, 8, 21, tzinfo=timezone.utc)
    current_time = [issued_at]
    store = RoomBootstrapStore(
        tmp_path / "bootstrap",
        now=lambda: current_time[0],
    )
    prepared = store.prepare_rehearsal_customer_invite(
        _draft(),
        bot_username="dualcoachtestbot",
        owner_id="12",
    )
    token = prepared.customer_link.rsplit("=", 1)[1]
    current_time[0] = issued_at + timedelta(hours=23, minutes=59)

    claimed = store.claim_rehearsal_customer_invite(
        token,
        user_id="10",
        chat_id="10",
        message_id="100",
    )

    assert claimed.state is BootstrapState.REGISTERING
    with pytest.raises(BootstrapError, match="unavailable"):
        _ = store.claim_rehearsal_customer_invite(
            token,
            user_id="10",
            chat_id="10",
            message_id="101",
        )
