"""WhatsApp integration — settings, test, login credential delivery."""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.dependencies import get_current_company_id
from app.core.security import get_current_user, get_password_hash
from app.models.user import User
from app.schemas.whatsapp import (
    SendLoginWhatsAppRequest,
    SendLoginWhatsAppResponse,
    WhatsAppSettingsResponse,
    WhatsAppSettingsUpdate,
    WhatsAppTestResponse,
)
from app.services.login_credentials_service import build_login_message_for_user
from app.services.whatsapp_service import WhatsAppService
from app.services.whatsapp_settings_service import get_whatsapp_settings, save_whatsapp_settings

router = APIRouter()


def _require_admin(user: User) -> None:
    if (user.role or "").lower() not in ("super_admin", "admin"):
        raise HTTPException(status_code=403, detail="Administrator access required")


def _settings_response(db: Session) -> WhatsAppSettingsResponse:
    raw = get_whatsapp_settings(db)
    svc = WhatsAppService(db)
    return WhatsAppSettingsResponse(
        whatsapp_enabled=raw.get("whatsapp_enabled", "false").lower() == "true",
        whatsapp_api_provider=raw.get("whatsapp_api_provider") or "whatsapp_business",
        whatsapp_business_token_set=bool(raw.get("whatsapp_business_token")),
        whatsapp_business_phone_id=raw.get("whatsapp_business_phone_id") or "",
        twilio_account_sid_set=bool(raw.get("twilio_account_sid")),
        twilio_auth_token_set=bool(raw.get("twilio_auth_token")),
        twilio_whatsapp_number=raw.get("twilio_whatsapp_number") or "",
        configured=svc.is_enabled(),
    )


@router.get("/settings", response_model=WhatsAppSettingsResponse)
def get_whatsapp_integration_settings(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    _require_admin(current_user)
    return _settings_response(db)


@router.put("/settings", response_model=WhatsAppSettingsResponse)
def update_whatsapp_integration_settings(
    body: WhatsAppSettingsUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    _require_admin(current_user)
    current = get_whatsapp_settings(db)
    updates = body.model_dump(exclude_unset=True)
    payload = {}
    for key, val in updates.items():
        if key == "whatsapp_enabled":
            payload[key] = "true" if val else "false"
        elif key in ("whatsapp_business_token", "twilio_auth_token", "twilio_account_sid"):
            if val == "":
                continue
            if val and not str(val).startswith("****"):
                payload[key] = str(val)
        else:
            payload[key] = val
    if "whatsapp_enabled" not in payload and "whatsapp_enabled" in updates:
        payload["whatsapp_enabled"] = "true" if updates["whatsapp_enabled"] else "false"
    merged = {**current, **payload}
    save_whatsapp_settings(db, merged)
    return _settings_response(db)


@router.post("/test", response_model=WhatsAppTestResponse)
def test_whatsapp_connection(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    _require_admin(current_user)
    result = WhatsAppService(db).test_connection()
    if result.get("success"):
        return WhatsAppTestResponse(
            success=True,
            message="Connected to WhatsApp API",
            provider=result.get("provider"),
            display_phone_number=result.get("display_phone_number"),
        )
    return WhatsAppTestResponse(success=False, message=result.get("error") or "Connection failed")


@router.post("/send-login", response_model=SendLoginWhatsAppResponse)
def send_login_via_whatsapp(
    body: SendLoginWhatsAppRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    company_id: str | None = Depends(get_current_company_id),
):
    _require_admin(current_user)
    svc = WhatsAppService(db)
    if not svc.is_enabled():
        raise HTTPException(
            status_code=400,
            detail="WhatsApp is not enabled. Configure Meta WhatsApp Business under Settings → WhatsApp.",
        )

    if body.user_id:
        target = db.query(User).filter(User.id == body.user_id).first()
        if not target:
            raise HTTPException(status_code=404, detail="User not found")
        if company_id and target.company_id and target.company_id != company_id:
            raise HTTPException(status_code=403, detail="User is not in your company")
        prefer_cloud = body.prefer_cloud
    else:
        target = current_user
        prefer_cloud = True

    phone = (body.phone_number or target.phone or "").strip()
    if not phone:
        raise HTTPException(status_code=400, detail="Phone number is required.")

    password_plain = body.temporary_password if body.include_password else None
    if body.include_password and not password_plain:
        raise HTTPException(
            status_code=400,
            detail="include_password requires temporary_password (e.g. from user creation).",
        )

    try:
        card = build_login_message_for_user(
            db,
            user=target,
            company_id=company_id or target.company_id,
            password_plain=password_plain,
            custom_note=body.custom_message,
            prefer_cloud=prefer_cloud,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    message = card["message"]
    result = svc.send_custom_message(phone, message)
    if not result.get("success"):
        raise HTTPException(status_code=400, detail=result.get("error") or "Failed to send WhatsApp message")

    if body.phone_number and target.id != current_user.id:
        target.phone = phone
        db.commit()

    return SendLoginWhatsAppResponse(
        success=True,
        message="Login details sent via WhatsApp",
        phone_number=phone,
        preview=message[:200] + ("…" if len(message) > 200 else ""),
    )
