"""resolve_email_delivery's platform_domain branch — managed email domain vs shared default.

Tier order under test: connector (BYOK) > platform_domain (managed domain, quota-gated) >
internal (shared default sender). A quota denial on the managed-domain tier must be final —
it must never silently fall through to the shared default sender (see
src/domain/email_domains service.py PR notes: that would both confuse recipients about who
is emailing them and defeat the paywall).
"""
from __future__ import annotations

from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4

import pytest

from src.domain.cloud.email_delivery import resolve_email_delivery
from src.domain.email_domains.service import QuotaDecision


def _connector_service_no_match():
    return SimpleNamespace(resolve_email_send=AsyncMock(return_value=None))


def _email_domain_repo(domain=None):
    return SimpleNamespace(get_by_workspace=AsyncMock(return_value=domain))


def _quota_service(decision: QuotaDecision):
    return SimpleNamespace(check_and_reserve=AsyncMock(return_value=decision))


@pytest.mark.asyncio
async def test_no_managed_domain_falls_back_to_internal(monkeypatch):
    monkeypatch.setattr(
        "src.domain.cloud.email_delivery.cloud_email_transport_configured", lambda settings: True
    )
    monkeypatch.setattr(
        "src.domain.cloud.email_delivery.normalized_cloud_email_provider", lambda settings: "resend"
    )
    policy = await resolve_email_delivery(
        connector_service=_connector_service_no_match(),
        workspace_id=uuid4(),
        project_id=uuid4(),
        enabled_capabilities=set(),
        email_domain_repo=_email_domain_repo(domain=None),
        email_quota_service=_quota_service(QuotaDecision(allowed=True)),
    )
    assert policy.delivery_scope == "internal"


@pytest.mark.asyncio
async def test_unverified_domain_falls_back_to_internal(monkeypatch):
    monkeypatch.setattr(
        "src.domain.cloud.email_delivery.cloud_email_transport_configured", lambda settings: True
    )
    monkeypatch.setattr(
        "src.domain.cloud.email_delivery.normalized_cloud_email_provider", lambda settings: "resend"
    )
    pending_domain = SimpleNamespace(domain="mail.example.com", status="pending_dns")
    policy = await resolve_email_delivery(
        connector_service=_connector_service_no_match(),
        workspace_id=uuid4(),
        project_id=uuid4(),
        enabled_capabilities=set(),
        email_domain_repo=_email_domain_repo(domain=pending_domain),
        email_quota_service=_quota_service(QuotaDecision(allowed=True)),
    )
    assert policy.delivery_scope == "internal"


@pytest.mark.asyncio
async def test_verified_domain_within_quota_uses_platform_domain_scope():
    verified_domain = SimpleNamespace(
        domain="mail.example.com", status="verified", ses_configuration_set_name="ws-abc"
    )
    policy = await resolve_email_delivery(
        connector_service=_connector_service_no_match(),
        workspace_id=uuid4(),
        project_id=uuid4(),
        enabled_capabilities=set(),
        email_domain_repo=_email_domain_repo(domain=verified_domain),
        email_quota_service=_quota_service(QuotaDecision(allowed=True)),
    )
    assert policy.allowed
    assert policy.delivery_scope == "platform_domain"
    assert policy.provider == "ses"
    assert policy.email_from == "noreply@mail.example.com"
    assert policy.email_configuration_set == "ws-abc"


@pytest.mark.asyncio
async def test_verified_domain_quota_denied_never_falls_back_to_internal():
    verified_domain = SimpleNamespace(
        domain="mail.example.com", status="verified", ses_configuration_set_name="ws-abc"
    )
    policy = await resolve_email_delivery(
        connector_service=_connector_service_no_match(),
        workspace_id=uuid4(),
        project_id=uuid4(),
        enabled_capabilities=set(),
        email_domain_repo=_email_domain_repo(domain=verified_domain),
        email_quota_service=_quota_service(
            QuotaDecision(allowed=False, reason_code="email_daily_cap_exceeded", message="nope")
        ),
    )
    assert not policy.allowed
    assert policy.reason_code == "email_daily_cap_exceeded"
    assert policy.delivery_scope != "internal"
