// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "polkit_auth.h"
#include "log.h"

bool polkit_check_authorization(const char *sender, const char *action_id)
{
    if (!sender || !action_id) {
        log_warning("polkit_check_authorization: invalid parameters");
        return false;
    }

    GError *error = NULL;
    bool authorized = false;

    // Get the polkit authority
    PolkitAuthority *authority = polkit_authority_get_sync(NULL, &error);
    if (!authority) {
        log_warning("Failed to get polkit authority: %s",
                    error ? error->message : "unknown error");
        g_clear_error(&error);
        return false;
    }

    // Create a subject from the D-Bus sender bus name
    PolkitSubject *subject = polkit_system_bus_name_new(sender);
    if (!subject) {
        log_warning("Failed to create polkit subject for sender: %s", sender);
        g_object_unref(authority);
        return false;
    }

    // Check authorization with user interaction (allows password dialog)
    PolkitAuthorizationResult *result = polkit_authority_check_authorization_sync(
        authority,
        subject,
        action_id,
        NULL, // details
        POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION, // allow interactive auth
        NULL, // cancellable
        &error);

    if (!result) {
        log_warning("Failed to check authorization for action '%s': %s",
                    action_id,
                    error ? error->message : "unknown error");
        g_clear_error(&error);
        g_object_unref(subject);
        g_object_unref(authority);
        return false;
    }

    authorized = polkit_authorization_result_get_is_authorized(result);

    log_debug("polkit authorization check: sender=%s, action=%s, authorized=%s",
              sender,
              action_id,
              authorized ? "yes" : "no");

    g_object_unref(result);
    g_object_unref(subject);
    g_object_unref(authority);

    return authorized;
}
