import hashlib
import hmac
import io
import re
import secrets
from datetime import timedelta
from pathlib import Path

from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.db import IntegrityError, transaction
from django.db.models import F, Q
from django.utils import timezone
from PIL import Image, ImageOps, UnidentifiedImageError

from apps.accounts_rbac.models import (
    CompanyMembership,
    ContactVerificationChallenge,
    Device,
    StaffAccessCredential,
    User,
    UserAvatar,
    UserSecurityEvent,
)
from apps.audit.services import record_audit_event

PRIVILEGED_CODE_BLOCKED_ROLES = {
    "SUPER_ADMIN",
    "COMPANY_ADMIN",
    "IT_ADMIN",
    "FINANCE_DIRECTOR",
    "FINANCE_MANAGER",
}


def _staff_code_fingerprint(code: str) -> str:
    pepper = (getattr(settings, "STAFF_CODE_PEPPER", None) or settings.SECRET_KEY).encode("utf-8")
    return hmac.new(pepper, f"maya-staff-code:{code}".encode("utf-8"), hashlib.sha256).hexdigest()


def _is_weak_staff_code(code: str, forbidden_tokens: list[str] | None = None) -> bool:
    if len(set(code)) == 1:
        return True
    if code in ("123456", "654321", "012345", "543210", "112233", "121212"):
        return True
    # Check strictly increasing/decreasing step-1 runs across 6 digits
    digits = [int(c) for c in code]
    if all(digits[i] + 1 == digits[i + 1] for i in range(5)) or all(digits[i] - 1 == digits[i + 1] for i in range(5)):
        return True
    for tok in forbidden_tokens or []:
        clean = re.sub(r"\D", "", str(tok or ""))
        if len(clean) >= 4 and clean in code:
            return True
        if len(clean) >= 6 and code in clean:
            return True
    return False


class UserSecurityAuditService:
    @staticmethod
    def record(*, user: User, event_type: str, actor: User | None = None, device_id: str = "", ip_address: str | None = None, status: str = "INFO", details: dict | None = None) -> UserSecurityEvent:
        safe_details = {
            k: v
            for k, v in (details or {}).items()
            if not any(s in k.lower() for s in ("password", "staff_code", "secret", "token", "hash"))
        }
        ev = UserSecurityEvent.objects.create(
            user=user,
            actor=actor,
            event_type=event_type,
            device_id=device_id or "",
            ip_address=ip_address,
            status=status,
            details=safe_details,
        )
        record_audit_event(
            actor=actor or user,
            action=event_type,
            entity_type="UserSecurity",
            entity_id=str(user.id),
            device_id=device_id or "",
            ip_address=ip_address,
            new_state=safe_details,
        )
        return ev


class StaffCodeGenerationService:
    @staticmethod
    @transaction.atomic
    def generate_and_assign(
        *,
        user: User,
        actor: User | None = None,
        forbidden_tokens: list[str] | None = None,
        expires_days: int | None = 180,
        must_change: bool = True,
        ip_address: str | None = None,
    ) -> str:
        tokens = list(forbidden_tokens or [])
        tokens.extend([user.mobile_number, user.username])
        emp = getattr(user, "staff_employee", None)
        if emp:
            tokens.extend([emp.employee_profile.employee_code, str(emp.date_of_birth or ""), emp.emergency_contact_phone])

        for _ in range(40):
            candidate = str(secrets.randbelow(900000) + 100000)
            if _is_weak_staff_code(candidate, tokens):
                continue
            fp = _staff_code_fingerprint(candidate)
            if StaffAccessCredential.objects.filter(staff_code_fingerprint=fp).exists():
                continue

            hashed = make_password(candidate)
            expires_at = timezone.now() + timedelta(days=expires_days) if expires_days else None
            try:
                StaffAccessCredential.objects.update_or_create(
                    user=user,
                    defaults={
                        "staff_code_hash": hashed,
                        "staff_code_fingerprint": fp,
                        "code_login_enabled": True,
                        "code_changed_at": timezone.now(),
                        "code_expires_at": expires_at,
                        "failed_attempt_count": 0,
                        "locked_until": None,
                        "must_change_code": must_change,
                    },
                )
            except IntegrityError:
                continue

            UserSecurityAuditService.record(
                user=user,
                actor=actor or user,
                event_type="STAFF_CODE_GENERATED",
                ip_address=ip_address,
                status="SUCCESS",
                details={"expires_at": expires_at.isoformat() if expires_at else None, "code_masked": "******"},
            )
            return candidate

        raise RuntimeError("Unable to allocate unique 6-digit staff login code after bounded retries.")


class StaffCodeResetService:
    @staticmethod
    def admin_reset(*, user: User, actor: User, expires_days: int | None = 180, ip_address: str | None = None) -> str:
        code = StaffCodeGenerationService.generate_and_assign(
            user=user,
            actor=actor,
            expires_days=expires_days,
            must_change=True,
            ip_address=ip_address,
        )
        UserSecurityAuditService.record(
            user=user,
            actor=actor,
            event_type="STAFF_CODE_ADMIN_RESET",
            ip_address=ip_address,
            status="SUCCESS",
            details={"reset_by": actor.username},
        )
        return code

    @staticmethod
    @transaction.atomic
    def self_change(*, user: User, new_code: str, current_password: str = "", current_code: str = "", ip_address: str | None = None) -> None:
        if not re.fullmatch(r"\d{6}", str(new_code or "")):
            raise ValueError("Staff code must be exactly 6 numeric digits (100000-999999).")
        if int(new_code) < 100000:
            raise ValueError("Staff code must be between 100000 and 999999.")

        if current_password:
            if not user.check_password(current_password):
                raise ValueError("Current password is incorrect.")
        elif current_code:
            cred = getattr(user, "staff_credential", None)
            if not cred or not check_password(current_code, cred.staff_code_hash):
                raise ValueError("Current staff code is incorrect.")
        else:
            raise ValueError("Re-authentication with current password or current code is required.")

        tokens = [user.mobile_number, user.username]
        emp = getattr(user, "staff_employee", None)
        if emp:
            tokens.extend([emp.employee_profile.employee_code, str(emp.date_of_birth or "")])
        if _is_weak_staff_code(new_code, tokens):
            raise ValueError("Selected code is too predictable or matches personal details.")

        fp = _staff_code_fingerprint(new_code)
        if StaffAccessCredential.objects.filter(staff_code_fingerprint=fp).exclude(user=user).exists():
            raise ValueError("This 6-digit code is unavailable. Choose a different combination.")

        StaffAccessCredential.objects.update_or_create(
            user=user,
            defaults={
                "staff_code_hash": make_password(new_code),
                "staff_code_fingerprint": fp,
                "code_login_enabled": True,
                "code_changed_at": timezone.now(),
                "code_expires_at": timezone.now() + timedelta(days=180),
                "failed_attempt_count": 0,
                "locked_until": None,
                "must_change_code": False,
            },
        )
        UserSecurityAuditService.record(
            user=user,
            actor=user,
            event_type="STAFF_CODE_SELF_CHANGED",
            ip_address=ip_address,
            status="SUCCESS",
            details={"code_masked": "******"},
        )

    @staticmethod
    def toggle_code_login(*, user: User, enabled: bool, actor: User | None = None, ip_address: str | None = None) -> dict:
        cred = getattr(user, "staff_credential", None)
        if not cred:
            raise ValueError("Staff member does not have a 6-digit credential assigned.")
        cred.code_login_enabled = enabled
        cred.save(update_fields=["code_login_enabled"])
        UserSecurityAuditService.record(
            user=user,
            actor=actor or user,
            event_type="STAFF_CODE_LOGIN_TOGGLED",
            ip_address=ip_address,
            status="SUCCESS",
            details={"code_login_enabled": enabled},
        )
        return {"code_login_enabled": cred.code_login_enabled}


def _resolve_user_by_identifier(identifier: str) -> User | None:
    ident = (identifier or "").strip()
    if not ident:
        return None
    return User.objects.filter(Q(username__iexact=ident) | Q(email__iexact=ident)).first()


def _assert_user_eligible_for_login(user: User, *, check_code_eligibility: bool = False) -> None:
    if not user.is_active:
        raise PermissionError("User account is disabled.")
    emp = getattr(user, "staff_employee", None)
    if emp and emp.status in ("SUSPENDED", "RESIGNED", "TERMINATED", "ARCHIVED"):
        raise PermissionError(f"Employee access disabled (employment status: {emp.status}).")
    if not CompanyMembership.objects.filter(user=user, is_active=True, company__is_active=True).exists() and not user.is_superuser:
        raise PermissionError("No active company assignment found for this account.")

    if check_code_eligibility:
        if user.is_superuser or user.mfa_enabled:
            raise PermissionError("Privileged or MFA-protected accounts must sign in with Password + MFA.")
        role_codes = set(
            CompanyMembership.objects.filter(user=user, is_active=True).values_list("role__code", flat=True)
        )
        extra_codes = set(
            CompanyMembership.objects.filter(user=user, is_active=True).values_list("roles__code", flat=True)
        )
        if (role_codes | extra_codes) & PRIVILEGED_CODE_BLOCKED_ROLES:
            raise PermissionError("Administrative & senior financial roles cannot bypass password/MFA with 6-digit staff code login.")


class UserAuthenticationService:
    @staticmethod
    def login_with_password(*, request, identifier: str, password: str, remember_me: bool = False, totp_code: str = "") -> User:
        from apps.accounts_rbac.services.mfa_and_security import LoginProtectionService, MfaEnrollmentService

        ident = (identifier or "").strip()
        ip = request.META.get("REMOTE_ADDR")
        device_id = request.headers.get("X-Device-ID", "")
        LoginProtectionService.assert_not_locked(ident, ip)

        user = _resolve_user_by_identifier(ident)
        username_to_auth = user.username if user else ident

        if user and not user.is_active and user.check_password(password):
            UserSecurityAuditService.record(
                user=user, event_type="DISABLED_ACCOUNT_LOGIN_BLOCKED", device_id=device_id, ip_address=ip, status="DENIED"
            )
            raise PermissionError("User account is disabled.")

        authed = authenticate(request, username=username_to_auth, password=password)
        if authed is None:
            LoginProtectionService.record_failure(identifier=ident, ip=ip, user=user, reason="Invalid password")
            if user:
                UserSecurityAuditService.record(
                    user=user, event_type="PASSWORD_LOGIN_FAILED", device_id=device_id, ip_address=ip, status="FAILED"
                )
            raise ValueError("Invalid username/email or password.")

        _assert_user_eligible_for_login(authed, check_code_eligibility=False)

        if authed.mfa_enabled:
            if not totp_code:
                raise PermissionError("MFA_REQUIRED: Enter your 6-digit authenticator or recovery code.")
            if not MfaEnrollmentService.verify_login_challenge(user=authed, code=totp_code):
                LoginProtectionService.record_failure(identifier=ident, ip=ip, user=authed, reason="Invalid MFA code")
                raise PermissionError("Invalid MFA verification code.")
        elif MfaEnrollmentService.is_mfa_mandatory_for_user(authed):
            raise PermissionError("MFA_ENROLLMENT_REQUIRED: Privileged accounts must enable MFA.")

        LoginProtectionService.clear_failures(identifier=ident, ip=ip)
        login(request, authed)
        if remember_me:
            request.session.set_expiry(60 * 60 * 24 * 14)
        else:
            request.session.set_expiry(0)

        UserSecurityAuditService.record(
            user=authed, event_type="PASSWORD_LOGIN_SUCCESS", device_id=device_id, ip_address=ip, status="SUCCESS"
        )
        return authed


class StaffCodeAuthenticationService:
    MAX_FAILED_CODE_ATTEMPTS = 5
    LOCKOUT_MINUTES = 15

    @staticmethod
    def login_with_staff_code(*, request, identifier: str, staff_code: str) -> User:
        ip = request.META.get("REMOTE_ADDR") or "unknown"
        device_id = request.headers.get("X-Device-ID", "")
        ident = (identifier or "").strip()

        ip_key = f"staff_code_ip_fail:{ip}"
        if (cache.get(ip_key) or 0) >= 15:
            raise PermissionError("Too many staff code attempts from this network address. Try again shortly.")

        user = _resolve_user_by_identifier(ident)
        if not user:
            cache.set(ip_key, (cache.get(ip_key) or 0) + 1, timeout=900)
            raise ValueError("Invalid username/email or staff login code.")

        _assert_user_eligible_for_login(user, check_code_eligibility=True)
        cred = getattr(user, "staff_credential", None)
        if not cred or not cred.code_login_enabled:
            raise PermissionError("6-digit staff code login is disabled for this account.")
        if not cred.allow_without_trusted_device and device_id:
            if not Device.objects.filter(user=user, device_id=device_id, status=Device.Status.ACTIVE).exists():
                raise PermissionError("Trusted registered device required for staff code login.")
        if cred.locked_until and cred.locked_until > timezone.now():
            raise PermissionError("Staff code temporarily locked due to failed attempts.")
        if cred.code_expires_at and cred.code_expires_at < timezone.now():
            raise PermissionError("Staff login code has expired. Request a reset from HR or IT Admin.")

        if not check_password(str(staff_code or "").strip(), cred.staff_code_hash):
            cred.failed_attempt_count += 1
            if cred.failed_attempt_count >= StaffCodeAuthenticationService.MAX_FAILED_CODE_ATTEMPTS:
                cred.locked_until = timezone.now() + timedelta(minutes=StaffCodeAuthenticationService.LOCKOUT_MINUTES)
            cred.save(update_fields=["failed_attempt_count", "locked_until"])
            cache.set(ip_key, (cache.get(ip_key) or 0) + 1, timeout=900)
            UserSecurityAuditService.record(
                user=user,
                event_type="STAFF_CODE_LOGIN_FAILED",
                device_id=device_id,
                ip_address=None if ip == "unknown" else ip,
                status="FAILED",
                details={"failed_attempt_count": cred.failed_attempt_count},
            )
            raise ValueError("Invalid username/email or staff login code.")

        cred.failed_attempt_count = 0
        cred.locked_until = None
        cred.last_code_login_at = timezone.now()
        cred.save(update_fields=["failed_attempt_count", "locked_until", "last_code_login_at"])
        cache.delete(ip_key)

        authed_backend = "django.contrib.auth.backends.ModelBackend"
        login(request, user, backend=authed_backend)
        UserSecurityAuditService.record(
            user=user,
            event_type="STAFF_CODE_LOGIN_SUCCESS",
            device_id=device_id,
            ip_address=None if ip == "unknown" else ip,
            status="SUCCESS",
        )
        return user


class UserAvatarService:
    ALLOWED_FORMATS = {"JPEG": "JPG", "PNG": "PNG", "WEBP": "WEBP"}
    MAX_BYTES = 5 * 1024 * 1024  # 5 MB

    @staticmethod
    def _avatar_dir(user_id) -> Path:
        root = Path(settings.PRIVATE_DOCUMENT_ROOT) / "avatars" / str(user_id)
        root.mkdir(parents=True, exist_ok=True)
        return root

    @staticmethod
    @transaction.atomic
    def upload_avatar(*, user: User, file_obj, ip_address: str | None = None) -> UserAvatar:
        raw = file_obj.read()
        if len(raw) == 0 or len(raw) > UserAvatarService.MAX_BYTES:
            raise ValueError("Avatar file must be non-empty and under 5 MB.")

        try:
            with Image.open(io.BytesIO(raw)) as probe:
                fmt = (probe.format or "").upper()
                probe.verify()
        except (UnidentifiedImageError, Exception) as exc:
            raise ValueError("Uploaded file is not a valid JPG, PNG, or WebP image.") from exc

        if fmt not in UserAvatarService.ALLOWED_FORMATS:
            raise ValueError(f"Unsupported image format: {fmt}. Only JPG, PNG, WebP allowed.")

        with Image.open(io.BytesIO(raw)) as img:
            img = ImageOps.exif_transpose(img)
            mode = "RGBA" if img.mode in ("RGBA", "LA", "P") else "RGB"
            clean_img = img.convert(mode)
            # EXIF stripped because we render clean pixel copy without info metadata
            clean_img.thumbnail((512, 512), Image.Resampling.LANCZOS)

            thumb = ImageOps.fit(clean_img, (128, 128), Image.Resampling.LANCZOS)

            out_dir = UserAvatarService._avatar_dir(user.id)
            main_path = out_dir / "avatar.webp"
            thumb_path = out_dir / "avatar_thumb.webp"
            clean_img.save(main_path, format="WEBP", quality=88)
            thumb.save(thumb_path, format="WEBP", quality=85)
            width, height = clean_img.size
            size_bytes = main_path.stat().st_size

        avatar, _ = UserAvatar.objects.update_or_create(
            user=user,
            defaults={
                "image_path": str(main_path),
                "thumbnail_path": str(thumb_path),
                "file_type": UserAvatarService.ALLOWED_FORMATS[fmt],
                "size_bytes": size_bytes,
                "width": width,
                "height": height,
            },
        )
        UserSecurityAuditService.record(
            user=user,
            actor=user,
            event_type="AVATAR_UPDATED",
            ip_address=ip_address,
            status="SUCCESS",
            details={"file_type": avatar.file_type, "size_bytes": size_bytes},
        )
        return avatar

    @staticmethod
    def remove_avatar(*, user: User, ip_address: str | None = None) -> None:
        av = getattr(user, "avatar", None)
        if av:
            Path(av.image_path).unlink(missing_ok=True)
            Path(av.thumbnail_path).unlink(missing_ok=True)
            av.delete()
            UserSecurityAuditService.record(
                user=user, actor=user, event_type="AVATAR_REMOVED", ip_address=ip_address, status="SUCCESS"
            )


class UserAccountService:
    @staticmethod
    def change_password(*, user: User, current_password: str, new_password: str, ip_address: str | None = None) -> None:
        if not user.check_password(current_password):
            raise ValueError("Current password is incorrect.")
        if len(new_password or "") < 8:
            raise ValueError("New password must be at least 8 characters.")
        user.set_password(new_password)
        user.must_reset_password = False
        user.save(update_fields=["password", "must_reset_password"])
        CompanyMembership.objects.filter(user=user).update(auth_version=F("auth_version") + 1)
        UserSecurityAuditService.record(
            user=user, actor=user, event_type="PASSWORD_CHANGED", ip_address=ip_address, status="SUCCESS"
        )


class UserSessionService:
    @staticmethod
    def list_my_sessions(user: User) -> list[dict]:
        devices = Device.objects.filter(user=user).select_related("company").order_by("-last_seen_at", "-registered_at")
        return [
            {
                "id": str(d.id),
                "device_id": d.device_id,
                "device_name": d.device_name,
                "platform": d.platform,
                "company_code": d.company.code,
                "status": d.status,
                "last_seen_at": d.last_seen_at.isoformat() if d.last_seen_at else None,
                "registered_at": d.registered_at.isoformat(),
            }
            for d in devices
        ]

    @staticmethod
    def revoke_my_device(*, user: User, device_pk: str, ip_address: str | None = None) -> None:
        dev = Device.objects.filter(user=user, id=device_pk).first()
        if not dev:
            raise ValueError("Device session not found.")
        dev.status = Device.Status.REVOKED
        dev.save(update_fields=["status"])
        CompanyMembership.objects.filter(user=user).update(auth_version=F("auth_version") + 1)
        UserSecurityAuditService.record(
            user=user, actor=user, event_type="SESSION_REVOKED", device_id=dev.device_id, ip_address=ip_address, status="SUCCESS"
        )

    @staticmethod
    def revoke_all_sessions(*, user: User, actor: User | None = None, ip_address: str | None = None) -> int:
        cnt = Device.objects.filter(user=user, status=Device.Status.ACTIVE).update(status=Device.Status.REVOKED)
        CompanyMembership.objects.filter(user=user).update(auth_version=F("auth_version") + 1)
        UserSecurityAuditService.record(
            user=user, actor=actor or user, event_type="ALL_SESSIONS_REVOKED", ip_address=ip_address, status="SUCCESS", details={"revoked_devices": cnt}
        )
        try:
            from apps.chat.consumers import broadcast_force_disconnect
            from apps.notifications.services import broadcast_notification_force_disconnect

            broadcast_force_disconnect(user.id)
            broadcast_notification_force_disconnect(user.id)
        except Exception:
            pass
        return cnt


class StaffProfileService:
    SELF_EDITABLE_USER_FIELDS = {
        "full_name",
        "mobile_number",
        "alt_mobile",
        "preferred_language",
        "timezone_name",
        "date_preference",
        "theme_preference",
    }
    SELF_EDITABLE_EMPLOYEE_FIELDS = {
        "personal_address",
        "province",
        "district",
        "local_level",
        "ward",
        "emergency_contact_name",
        "emergency_contact_phone",
    }

    @staticmethod
    @transaction.atomic
    def update_personal_details(*, user: User, data: dict, ip_address: str | None = None) -> dict:
        changed = {}
        user_fields_to_save = []
        for f in StaffProfileService.SELF_EDITABLE_USER_FIELDS:
            if f in data:
                old = getattr(user, f)
                val = data[f]
                if old != val:
                    setattr(user, f, val)
                    user_fields_to_save.append(f)
                    changed[f] = {"old": old, "new": val}
        if user_fields_to_save:
            user.save(update_fields=user_fields_to_save)

        emp = getattr(user, "staff_employee", None)
        if emp:
            emp_fields = []
            for f in StaffProfileService.SELF_EDITABLE_EMPLOYEE_FIELDS:
                if f in data:
                    old = getattr(emp, f)
                    val = data[f]
                    if old != val:
                        setattr(emp, f, val)
                        emp_fields.append(f)
                        changed[f] = {"old": old, "new": val}
            if emp_fields:
                emp.save(update_fields=emp_fields)
            if "full_name" in changed:
                emp.employee_profile.full_name = user.full_name
                emp.employee_profile.save(update_fields=["full_name"])

        if changed:
            UserSecurityAuditService.record(
                user=user, actor=user, event_type="PROFILE_SELF_UPDATED", ip_address=ip_address, status="SUCCESS", details={"changed": changed}
            )
        return changed

    @staticmethod
    def request_contact_verification(*, user: User, channel: str, new_contact: str, ip_address: str | None = None) -> dict:
        clean = (new_contact or "").strip()
        if not clean:
            raise ValueError("New contact value is required.")
        if channel == ContactVerificationChallenge.Channel.EMAIL:
            if User.objects.filter(email__iexact=clean).exclude(id=user.id).exists():
                raise ValueError("Email address is already in use by another account.")

        code = str(secrets.randbelow(900000) + 100000)
        ch = ContactVerificationChallenge.objects.create(
            user=user,
            channel=channel,
            new_contact=clean,
            code_hash=make_password(code),
            expires_at=timezone.now() + timedelta(minutes=15),
        )
        UserSecurityAuditService.record(
            user=user, actor=user, event_type="CONTACT_VERIFICATION_REQUESTED", ip_address=ip_address, status="INFO", details={"channel": channel, "new_contact": clean}
        )
        return {
            "challenge_id": str(ch.id),
            "channel": channel,
            "new_contact": clean,
            "expires_at": ch.expires_at.isoformat(),
            # Returned only in sandbox/dev notification mode for verification
            "dev_verification_code": code if settings.DEBUG else None,
        }

    @staticmethod
    @transaction.atomic
    def verify_and_apply_contact(*, user: User, challenge_id: str, verification_code: str, ip_address: str | None = None) -> dict:
        ch = ContactVerificationChallenge.objects.filter(id=challenge_id, user=user, is_consumed=False).first()
        if not ch:
            raise ValueError("Verification challenge not found or already used.")
        if ch.expires_at < timezone.now():
            raise ValueError("Verification code expired.")
        if not check_password(str(verification_code or "").strip(), ch.code_hash):
            raise ValueError("Verification code is invalid.")

        old_val = user.email if ch.channel == ContactVerificationChallenge.Channel.EMAIL else user.mobile_number
        if ch.channel == ContactVerificationChallenge.Channel.EMAIL:
            was_email_username = user.username.lower() == user.email.lower()
            user.email = ch.new_contact
            if was_email_username and not User.objects.filter(username__iexact=ch.new_contact).exclude(id=user.id).exists():
                user.username = ch.new_contact
            user.save(update_fields=["email", "username"])
            emp = getattr(user, "staff_employee", None)
            if emp:
                emp.employee_profile.email = ch.new_contact
                emp.employee_profile.save(update_fields=["email"])
        else:
            user.mobile_number = ch.new_contact
            user.save(update_fields=["mobile_number"])
            emp = getattr(user, "staff_employee", None)
            if emp:
                emp.employee_profile.phone = ch.new_contact
                emp.employee_profile.save(update_fields=["phone"])

        ch.verified_at = timezone.now()
        ch.is_consumed = True
        ch.save(update_fields=["verified_at", "is_consumed"])
        UserSecurityAuditService.record(
            user=user,
            actor=user,
            event_type="CONTACT_UPDATED_VERIFIED",
            ip_address=ip_address,
            status="SUCCESS",
            details={"channel": ch.channel, "old": old_val, "new": ch.new_contact},
        )
        return {"channel": ch.channel, "updated_to": ch.new_contact}

