from __future__ import annotations

import os
from unittest.mock import patch

from app.domain.contas.client import TimApiClient


def _real_client() -> TimApiClient:
    c = TimApiClient()
    c.mock = False
    return c


def test_vas_history_preserves_original_header_contract(monkeypatch):
    monkeypatch.setenv("TIM_VAS_HISTORY_URL", "http://mock/servicesHistory")
    monkeypatch.setenv("TIM_VAS_HISTORY_AUTH", "Basic token")
    monkeypatch.setenv("TIM_VAS_HISTORY_CLIENT_ID", "TIMX")
    monkeypatch.setenv("TIM_VAS_HISTORY_MESSAGE_ID", "msg-1")
    c = _real_client()
    with patch.object(c, "request", return_value={}) as req:
        c.historico_vas("12981114135")
    args, kwargs = req.call_args
    assert args[:2] == ("GET", "http://mock/servicesHistory?msisdn=12981114135")
    assert kwargs["headers"]["clientId"] == "TIMX"
    assert kwargs["headers"]["messageId"] == "msg-1"
    assert kwargs["headers"]["Authorization"] == "Basic token"


def test_contrato_uses_clientId_not_client_id(monkeypatch):
    monkeypatch.setenv("TIM_CONTRATO_URL", "http://test")
    monkeypatch.setenv("TIM_CONTRATO_AUTH", "Basic test")
    monkeypatch.setenv("TIM_CONTRATO_CLIENT_ID", "TEST")
    c = _real_client()
    with patch.object(c, "request", return_value={}) as req:
        c.contrato("11988888888")
    args, kwargs = req.call_args
    assert args[:2] == ("GET", "http://test/11988888888")
    assert kwargs["headers"]["clientId"] == "TEST"
    assert "client_id" not in kwargs["headers"]
    assert kwargs["headers"]["Authorization"] == "Basic test"


def test_profile_full_uses_original_ClientID_header(monkeypatch):
    monkeypatch.setenv("TIM_PROFILE_FULL_URL", "http://test/access/v1/info/{msisdn}")
    monkeypatch.setenv("TIM_PROFILE_FULL_AUTH", "Basic token")
    monkeypatch.setenv("TIM_PROFILE_FULL_CLIENT_ID", "AIAGENTCR")
    c = _real_client()
    with patch.object(c, "request", return_value={}) as req:
        c.profile_full("5511999999999")
    args, kwargs = req.call_args
    assert args[:2] == ("GET", "http://test/access/v1/info/5511999999999")
    assert kwargs["headers"]["ClientID"] == "AIAGENTCR"
    assert kwargs["headers"]["Authorization"] == "Basic token"


def test_cancelamento_always_sends_non_empty_message_id(monkeypatch):
    monkeypatch.setenv("TIM_CANCELAMENTO_URL", "http://test/cancel")
    c = _real_client()
    service = {"appId": "14534", "cspId": "740"}
    with patch.object(c, "request", return_value={"ok": True}) as req:
        c.cancelar_vas("11943896592", service, protocol="PROT-789")
    _args, kwargs = req.call_args
    assert kwargs["payload"]["channel"] == "AIAGENTCR"
    assert kwargs["payload"]["interactionProtocol"] == "PROT-789"
    assert kwargs["headers"]["messageId"]


def test_sms_preserva_sender_name_original(monkeypatch):
    from app.domain.contas.client import TimApiClient

    monkeypatch.setenv("TIM_USE_MOCK_GATEWAY", "false")
    monkeypatch.setenv("TIM_GATEWAY_MODE", "real")
    monkeypatch.setenv("TIM_SMS_URL", "http://test/sms")
    monkeypatch.setenv("TIM_SMS_AUTH", "Basic static")
    monkeypatch.setenv("TIM_SMS_CLIENT_ID", "CHAT")
    monkeypatch.setenv("TIM_SMS_SENDER_ADDRESS", "324")
    monkeypatch.delenv("TIM_SMS_SENDER_NAME", raising=False)
    client = TimApiClient()
    captured = {}

    def fake_request(method, url, **kwargs):
        captured.update({"method": method, "url": url, **kwargs})
        return {"resourceURL": "http://sms/1"}

    monkeypatch.setattr(client, "request", fake_request)
    client.sms("11999999999", "mensagem")
    assert captured["method"] == "POST"
    assert captured["payload"]["senderAddress"] == "324"
    assert captured["payload"]["senderName"] == "TIM Brasil"
    assert captured["payload"]["longURL"] == "mensagem"
    assert captured["headers"]["clientId"] == "CHAT"
    assert captured["headers"]["Authorization"] == "Basic static"


def test_service_request_status_message_id_prioriza_call_id(monkeypatch):
    from app.domain.contas.client import TimApiClient

    monkeypatch.setenv("TIM_USE_MOCK_GATEWAY", "false")
    monkeypatch.setenv("TIM_GATEWAY_MODE", "real")
    monkeypatch.setenv("TIM_SERVICE_REQUEST_STATUS_URL", "http://test/sr")
    client = TimApiClient()
    captured = {}

    def fake_request(method, url, **kwargs):
        captured.update({"method": method, "url": url, **kwargs})
        return {"ok": True}

    monkeypatch.setattr(client, "request", fake_request)
    client.status_sr({
        "channel": "AIAGENTCR",
        "protocolNumber": "PRT-123",
        "ura_call_id": "CALL-123",
        "session_id": "sess-1",
    })
    assert captured["payload"]["serviceRequest"]["protocolNumber"] == "PRT-123"
    assert captured["headers"]["messageId"] == "CALL-123"
