"""Business SMS dispatch through a pluggable SMS provider."""

import logging

from fastapi import HTTPException

from app.database import async_session
from app.services import system_setting_service
from app.services.provider_loader import create_sms_provider
from mode.sms.base import SmsProviderError, SmsVerificationMessage


log = logging.getLogger("qycw.sms")


async def send_verification_code(
    phone: str,
    code: str,
    purpose: str = "register",
    *,
    config_overrides: dict[str, object] | None = None,
) -> None:
    message = SmsVerificationMessage(phone=phone, code=code, purpose=purpose)
    try:
        async with async_session() as session:
            config = await system_setting_service.get_sms_provider_config(session, config_overrides)
        if not config.sms_enabled:
            raise SmsProviderError("sms service is disabled", status_code=400)
        await create_sms_provider(config).send_verification_code(message)
    except SmsProviderError as exc:
        log.warning("send sms to %s failed: %s", phone, exc.message)
        if "disabled" in exc.message:
            raise HTTPException(status_code=400, detail="短信服务未启用") from exc
        if "missing config" in exc.message or "not configured" in exc.message:
            raise HTTPException(status_code=500, detail="短信服务未配置") from exc
        if exc.status_code >= 500:
            raise HTTPException(status_code=500, detail="短信发送失败，请稍后重试") from exc
        raise HTTPException(status_code=exc.status_code, detail=exc.message) from exc


async def send_test_sms(phone: str, *, config_overrides: dict[str, object] | None = None) -> None:
    await send_verification_code(phone, "123456", purpose="login", config_overrides=config_overrides)
