"""Tests for duty_teller.api.telegram_auth.validate_init_data and validate_init_data_with_reason."""

from unittest.mock import patch

import duty_teller.config as config
from duty_teller.api.telegram_auth import (
    validate_init_data,
    validate_init_data_with_reason,
)
from tests.helpers import make_init_data


def test_valid_payload_returns_username():
    bot_token = "123:ABC"
    user = {"id": 123, "username": "testuser", "first_name": "Test"}
    init_data = make_init_data(user, bot_token)
    assert validate_init_data(init_data, bot_token) == "testuser"


def test_valid_payload_username_lowercase():
    bot_token = "123:ABC"
    user = {"id": 123, "username": "TestUser", "first_name": "Test"}
    init_data = make_init_data(user, bot_token)
    assert validate_init_data(init_data, bot_token) == "testuser"


def test_invalid_hash_returns_none():
    bot_token = "123:ABC"
    user = {"id": 123, "username": "testuser"}
    init_data = make_init_data(user, bot_token)
    # Tamper with hash
    init_data = init_data.replace("hash=", "hash=x")
    assert validate_init_data(init_data, bot_token) is None


def test_wrong_bot_token_returns_none():
    bot_token = "123:ABC"
    user = {"id": 123, "username": "testuser"}
    init_data = make_init_data(user, bot_token)
    assert validate_init_data(init_data, "other:token") is None


def test_missing_user_returns_none():
    bot_token = "123:ABC"
    init_data = make_init_data(None, bot_token)  # no user key
    assert validate_init_data(init_data, bot_token) is None


def test_user_without_username_returns_none_from_validate_init_data():
    """validate_init_data returns None when user has no username (backward compat)."""
    bot_token = "123:ABC"
    user = {"id": 123, "first_name": "Test"}  # no username
    init_data = make_init_data(user, bot_token)
    assert validate_init_data(init_data, bot_token) is None


def test_user_without_username_but_with_id_succeeds_with_reason():
    """With validate_init_data_with_reason, valid user.id is enough; lang is DEFAULT_LANGUAGE."""
    bot_token = "123:ABC"
    user = {"id": 456, "first_name": "Test", "language_code": "ru"}
    init_data = make_init_data(user, bot_token)
    telegram_user_id, username, reason, lang = validate_init_data_with_reason(
        init_data, bot_token
    )
    assert telegram_user_id == 456
    assert username is None
    assert reason == "ok"
    assert lang == config.DEFAULT_LANGUAGE


def test_user_without_id_returns_no_user_id():
    """When user object exists but has no 'id', return no_user_id; lang is DEFAULT_LANGUAGE."""
    bot_token = "123:ABC"
    user = {"first_name": "Test"}  # no id
    init_data = make_init_data(user, bot_token)
    telegram_user_id, username, reason, lang = validate_init_data_with_reason(
        init_data, bot_token
    )
    assert telegram_user_id is None
    assert username is None
    assert reason == "no_user_id"
    assert lang == config.DEFAULT_LANGUAGE


def test_validate_init_data_with_reason_returns_default_language_ignoring_user_lang():
    """Returned lang is always config.DEFAULT_LANGUAGE, not user.language_code."""
    with patch("duty_teller.api.telegram_auth.config.DEFAULT_LANGUAGE", "ru"):
        user = {"id": 1, "first_name": "U", "language_code": "en"}
        init_data = make_init_data(user, "123:ABC")
        _, _, reason, lang = validate_init_data_with_reason(init_data, "123:ABC")
        assert reason == "ok"
        assert lang == "ru"


def test_empty_init_data_returns_none():
    assert validate_init_data("", "token") is None
    assert validate_init_data("   ", "token") is None


def test_empty_bot_token_returns_none():
    user = {"id": 1, "username": "u"}
    init_data = make_init_data(user, "token")
    assert validate_init_data(init_data, "") is None


def test_auth_date_expiry_rejects_old_init_data():
    """When max_age_seconds is set, initData older than that is rejected."""
    import time as t

    bot_token = "123:ABC"
    user = {"id": 1, "username": "testuser"}
    # auth_date 100 seconds ago
    old_ts = int(t.time()) - 100
    init_data = make_init_data(user, bot_token, auth_date=old_ts)
    assert validate_init_data(init_data, bot_token, max_age_seconds=60) is None
    assert validate_init_data(init_data, bot_token, max_age_seconds=200) == "testuser"


def test_auth_date_expiry_accepts_fresh_init_data():
    """Fresh auth_date within max_age_seconds is accepted."""
    import time as t

    bot_token = "123:ABC"
    user = {"id": 1, "username": "testuser"}
    fresh_ts = int(t.time()) - 10
    init_data = make_init_data(user, bot_token, auth_date=fresh_ts)
    assert validate_init_data(init_data, bot_token, max_age_seconds=60) == "testuser"


def test_auth_date_expiry_requires_auth_date_when_max_age_set():
    """When max_age_seconds is set but auth_date is missing, return None."""
    bot_token = "123:ABC"
    user = {"id": 1, "username": "testuser"}
    init_data = make_init_data(user, bot_token)  # no auth_date
    assert validate_init_data(init_data, bot_token, max_age_seconds=86400) is None
    assert validate_init_data(init_data, bot_token) == "testuser"
