from pypos.core.base_service import BaseService
from pypos.core.utils.ui_message_utils import sanitize_ui_message
from pypos.modules.auth.models.auth_model import AuthModel
from pypos.modules.auth.services.auth_service import AuthService


class ChangePasswordService(BaseService):
    def __init__(self, model=None, auth_service=None):
        super().__init__()
        self.model = model or AuthModel()
        self.auth_service = auth_service or AuthService()

    def change_password(self, user_id, old_password, new_password, confirm_password):
        if user_id is None:
            return False, "User tidak valid."

        old_pwd = str(old_password or "")
        new_pwd = str(new_password or "")
        confirm_pwd = str(confirm_password or "")

        if not old_pwd or not new_pwd or not confirm_pwd:
            return False, "Semua field wajib diisi."
        if new_pwd != confirm_pwd:
            return False, "Konfirmasi password tidak sama."

        user = self.model.get_user_by_id(user_id)
        if not user:
            return False, "Data user tidak ditemukan."

        try:
            ok, _ = self.auth_service.verify_and_upgrade(old_pwd, user["password"])
        except RuntimeError as e:
            safe_message, _ = sanitize_ui_message("warning", str(e))
            return False, safe_message

        if not ok:
            return False, "Password lama salah."

        try:
            new_hash = self.auth_service.hash_password(new_pwd)
        except RuntimeError as e:
            safe_message, _ = sanitize_ui_message("warning", str(e))
            return False, safe_message

        self.model.update_password_hash_by_id(user_id, new_hash)
        return True, "Password berhasil diubah."

