'use strict';
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('api', {
    // Dev mode
    isDev: () => ipcRenderer.invoke('get-is-dev'),

    // Configuración
    getEnv:        ()       => ipcRenderer.invoke('get-env'),
    saveEnv:       (data)   => ipcRenderer.invoke('save-env', data),
    getVersion:    ()       => ipcRenderer.invoke('get-version'),
    openEnvFile:   ()       => ipcRenderer.invoke('open-env-file'),

    // Agenda / schedule
    getSchedule:       ()     => ipcRenderer.invoke('get-schedule'),
    saveSchedule:      (data) => ipcRenderer.invoke('save-schedule', data),
    saveScheduleLocal: (data) => ipcRenderer.invoke('save-schedule-local', data),

    // Worker process
    workerStart:     ()  => ipcRenderer.invoke('worker-start'),
    workerStop:      ()  => ipcRenderer.invoke('worker-stop'),
    workerIsRunning: ()  => ipcRenderer.invoke('worker-is-running'),

    // Vinculación de cuenta
    linkAccount: (opts) => ipcRenderer.invoke('link-account', opts),

    // API del servidor
    serverApi: (opts) => ipcRenderer.invoke('server-api', opts),

    // Eventos worker → renderer
    onWorkerStatus: (cb) => {
        ipcRenderer.removeAllListeners('worker-status');
        ipcRenderer.on('worker-status', (_, data) => cb(data));
    },
    onWorkerLog: (cb) => {
        ipcRenderer.removeAllListeners('worker-log');
        ipcRenderer.on('worker-log', (_, data) => cb(data));
    },
    onLinkAccountProgress: (cb) => {
        ipcRenderer.removeAllListeners('link-account-progress');
        ipcRenderer.on('link-account-progress', (_, data) => cb(data));
    },

    // Sesiones locales
    checkLocalSessions:    (usernames) => ipcRenderer.invoke('check-local-sessions', usernames),
    getAllLocalSessions:    ()          => ipcRenderer.invoke('get-all-local-sessions'),
    resetLocalSession:     (opts)      => ipcRenderer.invoke('reset-local-session', opts),

    // Challenge resolution
    resolveChallenge:    (opts) => ipcRenderer.invoke('resolve-challenge', opts),
    markChallengeReview: (opts) => ipcRenderer.invoke('mark-challenge-review', opts),

    // Tray popup → main window
    openMainWindow:    ()  => ipcRenderer.invoke('open-main-window'),
    hidePopup:         ()  => ipcRenderer.invoke('hide-popup'),
    openLinkFromPopup: ()  => ipcRenderer.invoke('open-link-from-popup'),
    getWorkerState:    ()  => ipcRenderer.invoke('get-worker-state'),

    // Utilidades
    openExternal: (url) => ipcRenderer.invoke('open-external', url),

    // Auto-updater (descarga via Node.js, sin Chrome, evita bloqueos de AV)
    autoUpdateCheck:    ()     => ipcRenderer.invoke('auto-update-check'),
    autoUpdateDownload: (opts) => ipcRenderer.invoke('auto-update-download', opts),
    autoUpdateApply:    (opts) => ipcRenderer.invoke('auto-update-apply', opts || {}),
    // Devuelve { updated, version } si la app acaba de actualizarse (marker en SCRIPT_DIR)
    checkJustUpdated:   ()     => ipcRenderer.invoke('check-just-updated'),
    // Evento: el servidor revocó la licencia → el worker se desinstala y se cierra
    onWorkerRevoked: (cb) => {
        ipcRenderer.removeAllListeners('worker-revoked');
        ipcRenderer.on('worker-revoked', (_, data) => cb(data));
    },
    onForceUpdate: (cb) => {
        ipcRenderer.removeAllListeners('force-update');
        ipcRenderer.on('force-update', (_, data) => cb(data));
    },
    onChallengeDetected: (cb) => {
        ipcRenderer.removeAllListeners('challenge-detected');
        ipcRenderer.on('challenge-detected', (_, data) => cb(data));
    },
    onChallengeResolveStatus: (cb) => {
        ipcRenderer.removeAllListeners('challenge-resolve-status');
        ipcRenderer.on('challenge-resolve-status', (_, data) => cb(data));
    },
    onUpdateProgress: (cb) => {
        ipcRenderer.removeAllListeners('update-progress');
        ipcRenderer.on('update-progress', (_, data) => cb(data));
    },

    // ID del worker (calculado igual que workerRuntime.js — no solo lo del .env)
    getWorkerId:           ()     => ipcRenderer.invoke('get-worker-id'),
    // Licencias
    getHwid:               ()     => ipcRenderer.invoke('get-hwid'),
    checkLicenseStatus:    ()     => ipcRenderer.invoke('check-license-status'),
    submitLicenseRequest:  (data) => ipcRenderer.invoke('submit-license-request', data),
    onLicenseUpdate: (cb) => {
        ipcRenderer.removeAllListeners('license-update');
        ipcRenderer.on('license-update', (_, data) => cb(data));
    },
    onOpenLinkModal: (cb) => {
        ipcRenderer.removeAllListeners('open-link-modal');
        ipcRenderer.on('open-link-modal', () => cb());
    },
});
