const listmonkService = require('../services/listmonk');
const nocodbService = require('../services/nocodb');
const logger = require('../utils/logger');

// Get Listmonk sync status
exports.getSyncStatus = async (req, res) => {
    try {
        const status = listmonkService.getSyncStatus();
        
        // Also check connection if it's enabled
        if (status.enabled && !status.connected) {
            // Try to reconnect
            const reconnected = await listmonkService.checkConnection();
            status.connected = reconnected;
        }
        
        res.json(status);
    } catch (error) {
        logger.error('Failed to get Listmonk status', error);
        res.status(500).json({ 
            success: false, 
            error: 'Failed to get sync status' 
        });
    }
};

// Bulk sync all locations to Listmonk
exports.syncAllLocations = async (req, res) => {
    try {
        if (!listmonkService.syncEnabled) {
            return res.status(400).json({
                success: false,
                error: 'Listmonk sync is disabled'
            });
        }

        const locationData = await nocodbService.getLocations();
        const locations = locationData?.list || [];
        
        if (!locations || locations.length === 0) {
            return res.json({
                success: true,
                message: 'No locations to sync',
                results: { total: 0, success: 0, failed: 0, errors: [] }
            });
        }

        const results = await listmonkService.bulkSync(locations, 'location');
        
        res.json({
            success: true,
            message: `Bulk location sync completed: ${results.success} succeeded, ${results.failed} failed`,
            results
        });
    } catch (error) {
        logger.error('Bulk location sync failed', error);
        res.status(500).json({
            success: false,
            error: 'Failed to sync locations to Listmonk'
        });
    }
};

// Bulk sync all users to Listmonk
exports.syncAllUsers = async (req, res) => {
    try {
        if (!listmonkService.syncEnabled) {
            return res.status(400).json({
                success: false,
                error: 'Listmonk sync is disabled'
            });
        }

        const config = require('../config');
        const userData = await nocodbService.getAllPaginated(config.nocodb.loginSheetId);
        const users = userData?.list || [];
        
        if (!users || users.length === 0) {
            return res.json({
                success: true,
                message: 'No users to sync',
                results: { total: 0, success: 0, failed: 0, errors: [] }
            });
        }

        const results = await listmonkService.bulkSync(users, 'user');
        
        res.json({
            success: true,
            message: `Bulk user sync completed: ${results.success} succeeded, ${results.failed} failed`,
            results
        });
    } catch (error) {
        logger.error('Bulk user sync failed', error);
        res.status(500).json({
            success: false,
            error: 'Failed to sync users to Listmonk'
        });
    }
};

// Sync both locations and users
exports.syncAll = async (req, res) => {
    try {
        if (!listmonkService.syncEnabled) {
            return res.status(400).json({
                success: false,
                error: 'Listmonk sync is disabled'
            });
        }

        let results = {
            locations: { total: 0, success: 0, failed: 0, errors: [] },
            users: { total: 0, success: 0, failed: 0, errors: [] }
        };

        // Sync locations
        try {
            const locationData = await nocodbService.getLocations();
            const locations = locationData?.list || [];
            if (locations && locations.length > 0) {
                results.locations = await listmonkService.bulkSync(locations, 'location');
            }
        } catch (error) {
            logger.error('Failed to sync locations during full sync', error);
            results.locations.errors.push({ error: error.message });
        }

        // Sync users
        try {
            const userData = await nocodbService.getAllPaginated(config.nocodb.loginSheetId);
            const users = userData?.list || [];
            if (users && users.length > 0) {
                results.users = await listmonkService.bulkSync(users, 'user');
            }
        } catch (error) {
            logger.error('Failed to sync users during full sync', error);
            results.users.errors.push({ error: error.message });
        }

        const totalSuccess = results.locations.success + results.users.success;
        const totalFailed = results.locations.failed + results.users.failed;

        res.json({
            success: true,
            message: `Complete sync finished: ${totalSuccess} succeeded, ${totalFailed} failed`,
            results
        });
    } catch (error) {
        logger.error('Complete sync failed', error);
        res.status(500).json({
            success: false,
            error: 'Failed to perform complete sync'
        });
    }
};

// Get Listmonk list statistics
exports.getListStats = async (req, res) => {
    try {
        if (!listmonkService.syncEnabled) {
            return res.json({
                success: false,
                error: 'Listmonk sync is disabled',
                stats: null
            });
        }

        const stats = await listmonkService.getListStats();
        
        // Convert stats object to array format for frontend
        let statsArray = [];
        if (stats && typeof stats === 'object') {
            statsArray = Object.entries(stats).map(([key, list]) => ({
                id: key,
                name: list.name,
                subscriberCount: list.subscriber_count || 0,
                description: `Email list for ${key}`
            }));
        }
        
        res.json({
            success: true,
            stats: statsArray
        });
    } catch (error) {
        logger.error('Failed to get Listmonk list stats', error);
        res.status(500).json({
            success: false,
            error: 'Failed to get list statistics'
        });
    }
};

// Test Listmonk connection
exports.testConnection = async (req, res) => {
    try {
        const connected = await listmonkService.checkConnection();
        
        if (connected) {
            res.json({
                success: true,
                message: 'Listmonk connection successful',
                connected: true
            });
        } else {
            res.json({
                success: false,
                message: listmonkService.lastError || 'Connection failed',
                connected: false
            });
        }
    } catch (error) {
        logger.error('Failed to test Listmonk connection', error);
        res.status(500).json({
            success: false,
            error: 'Failed to test connection'
        });
    }
};

// Reinitialize Listmonk lists
exports.reinitializeLists = async (req, res) => {
    try {
        if (!listmonkService.syncEnabled) {
            return res.status(400).json({
                success: false,
                error: 'Listmonk sync is disabled'
            });
        }

        const initialized = await listmonkService.initializeLists();
        
        if (initialized) {
            res.json({
                success: true,
                message: 'Listmonk lists reinitialized successfully'
            });
        } else {
            res.json({
                success: false,
                message: listmonkService.lastError || 'Failed to initialize lists'
            });
        }
    } catch (error) {
        logger.error('Failed to reinitialize Listmonk lists', error);
        res.status(500).json({
            success: false,
            error: 'Failed to reinitialize lists'
        });
    }
};
