import { ref } from 'vue';
import axios from 'axios';

export function useUltimate() {
    const loading = ref(false);
    const stats = ref(null);
    const queryResults = ref(null);
    const affectedRows = ref(0);
    const commandOutput = ref('');

    const getStats = async () => {
        loading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/stats');
            if (response.data.success) {
                stats.value = response.data.data;
            }
            return response.data;
        } catch (error) {
            console.error('Failed to fetch stats:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const runQuery = async (query) => {
        loading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/query', { query });
            if (response.data.success) {
                queryResults.value = response.data.data || null;
                affectedRows.value = response.data.affected || 0;
            }
            return response.data;
        } catch (error) {
            console.error('Failed to run query:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const toggleMaintenance = async (enabled) => {
        loading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/maintenance/toggle', { enabled });
            if (response.data.success && stats.value) {
                stats.value.maintenance_mode = response.data.maintenance_mode;
            }
            return response.data;
        } catch (error) {
            console.error('Failed to toggle maintenance:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const sendGlobalMessage = async (message, type = 'info') => {
        loading.value = true;
        try {
            return await axios.post('/admin/ultimate/global-message', { message, type });
        } catch (error) {
            console.error('Failed to send global message:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const flushData = async (target) => {
        loading.value = true;
        try {
            return await axios.post('/admin/ultimate/flush', { target });
        } catch (error) {
            console.error('Failed to flush data:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const testNotification = async (userHash) => {
        loading.value = true;
        try {
            return await axios.post('/admin/ultimate/test-notification', { user_hash: userHash });
        } catch (error) {
            console.error('Failed to test notification:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const batchManage = async (action, ids, data = {}) => {
        loading.value = true;
        try {
            return await axios.post('/admin/ultimate/batch', { action, ids, data });
        } catch (error) {
            console.error('Failed to run batch operation:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const runCommand = async (command) => {
        loading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/command', { command });
            if (response.data.success) {
                commandOutput.value = response.data.output;
            }
            return response.data;
        } catch (error) {
            console.error('Failed to run command:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const getLogs = async (type = 'database') => {
        loading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/logs', { type });
            return response.data;
        } catch (error) {
            console.error('Failed to fetch logs:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const downloadBackup = () => {
        // Simple window location change to trigger GET download
        window.location.href = '/admin/ultimate/backup/download';
    };

    const getBackups = async () => {
        loading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/backups/list');
            return response.data;
        } catch (error) {
            console.error('Failed to fetch backups:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const downloadBackupByHash = (hash) => {
        window.location.href = `/admin/ultimate/backup/download/hash?hash=${hash}`;
    };

    const renameBackup = async (hash, name) => {
        loading.value = true;
        try {
            return await axios.post('/admin/ultimate/backup/rename', { hash, name });
        } catch (error) {
            console.error('Failed to rename backup:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    const deleteBackup = async (hash) => {
        loading.value = true;
        try {
            return await axios.post('/admin/ultimate/backup/delete', { hash });
        } catch (error) {
            console.error('Failed to delete backup:', error);
            throw error;
        } finally {
            loading.value = false;
        }
    };

    return {
        loading,
        stats,
        queryResults,
        affectedRows,
        commandOutput,
        getStats,
        runQuery,
        toggleMaintenance,
        sendGlobalMessage,
        flushData,
        testNotification,
        batchManage,
        runCommand,
        getLogs,
        downloadBackup,
        getBackups,
        downloadBackupByHash,
        renameBackup,
        deleteBackup
    };
}
