#pragma once

#include <QObject>
#include <QList>
#include <QString>
#include <QDBusObjectPath>
#include <QDBusMessage>
#include <QHash>
#include "../core/user_types.h"

class UserService : public QObject {
    Q_OBJECT
public:
    explicit UserService(QObject* parent = nullptr);

    // Best-effort fetch from system DBus; falls back to mock if not available
    QList<UserRecord> fetchUsers();

    // Begin live monitoring of AccountsService for changes; safe to call once
    void startMonitoring();

    // Refresh a single user's current data (e.g. after external change)
    UserRecord fetchSingleByName(const QString& username);

    // Force a full refresh from AccountsService and emit incremental changes.
    // Useful after we perform useradd/userdel ourselves (pkexec) to keep UI consistent.
    void refresh();

signals:
    // Future: live updates (not implemented v1)
    void userAdded(const UserRecord& u);
    void userRemoved(const QString& username);
    void userUpdated(const UserRecord& u);

private slots:
    void handleUserAdded(const QDBusObjectPath& path);
    void handleUserRemoved(const QDBusObjectPath& path);
    void onUserChangedMsg(const QDBusMessage& msg);

private:
    QList<UserRecord> fetchViaDBus();
    QList<UserRecord> fetchMock();
    void connectSignals();
    void handleUserChanged(const QDBusObjectPath& path);
    UserRecord fetchViaPath(const QString& path);

    bool m_monitoringStarted = false;
    // map username -> object path for quick lookup
    QHash<QString, QString> m_userPathByName;

    // cached canonical view of users (username -> record)
    QHash<QString, UserRecord> m_usersByName;
};
