// dbRepository.js
// Couche d’accès aux données pour l’extension.
// Utilise le helper Python password_db.py pour manipuler SQLite.

import GLib from 'gi://GLib';
import Gio from 'gi://Gio';
import * as ExtensionUtils from 'resource:///org/gnome/shell/misc/extensionUtils.js';

const Me = ExtensionUtils.getCurrentExtension();

const APP_DATA_DIR = GLib.build_filenamev([
    GLib.get_home_dir(),
    '.local', 'share', 'gnome-shell', 'password-applet'
]);

export class PasswordRepository {
    constructor() {
        this._helperPath = Me.dir.get_child('password_db.py').get_path();
    }

    init() {
        if (!GLib.file_test(APP_DATA_DIR, GLib.FileTest.IS_DIR)) {
            GLib.mkdir_with_parents(APP_DATA_DIR, 0o700);
        }
        this._runHelperSync(['init']);
    }

    listEntries() {
        const stdout = this._runHelperSync(['list']);
        if (!stdout)
            return [];

        try {
            return JSON.parse(stdout);
        } catch (e) {
            logError(e, 'Erreur JSON listEntries');
            return [];
        }
    }

    addEntry(entry) {
        const payload = JSON.stringify(entry);
        this._runHelperSync(['add'], payload);
    }

    _runHelperSync(args, stdinText = '') {
        const argv = ['python3', this._helperPath, ...args];

        const proc = new Gio.Subprocess({
            argv,
            flags: Gio.SubprocessFlags.STDOUT_PIPE |
                   Gio.SubprocessFlags.STDERR_PIPE,
        });

        try {
            proc.init(null);
        } catch (e) {
            logError(e, 'Impossible de lancer password_db.py');
            return '';
        }

        const [ok, stdout, stderr] = proc.communicate_utf8(stdinText, null);

        if (!ok || !proc.get_successful()) {
            log(`password_db.py error: ${stderr}`);
            return '';
        }

        return stdout.trim();
    }
}
