const websiteModel = require('../models/website.model');

const depositModel = require('../models/deposit.model');

const fs = require('fs');
const path = require('path');

const maskEmail = (email) => {
    const name = email.split('@')[0];
    return name.slice(0, 4) + '******';
};

class WebsiteService {
    async getWebsite() {
        return await websiteModel.findOne();
    }

    async topDeposit() {
        const data = await depositModel.aggregate([
            { $match: { status: 'success' } },
            {
                $group: {
                    _id: '$userId',
                    totalDeposit: { $sum: '$receivedAmount' },
                },
            },
            { $sort: { totalDeposit: -1 } },
            { $limit: 5 },
            {
                $lookup: {
                    from: 'users',
                    localField: '_id',
                    foreignField: '_id',
                    as: 'user',
                },
            },
            { $unwind: '$user' },
            {
                $project: {
                    _id: 0,
                    totalDeposit: 1,
                    email: '$user.email',
                },
            },
        ]);
        const result = data.map((item) => ({
            totalDeposit: item.totalDeposit,
            email: maskEmail(item.email),
        }));
        return result;
    }

    async updateWebsite(data) {
        const website = await websiteModel.findOne();
        if (!website) {
            return await websiteModel.create(data);
        }

        const deleteFile = (filename) => {
            if (!filename) return;
            try {
                // filename stored as /filename.ext, remove leading /
                const filePath = path.join(
                    __dirname,
                    '../uploads/websites',
                    filename.startsWith('/') ? filename.slice(1) : filename,
                );
                if (fs.existsSync(filePath)) {
                    fs.unlinkSync(filePath);
                }
            } catch (error) {
                console.error('Error deleting file:', error);
            }
        };

        // Handle single image updates (logo, favicon)
        if (data.logo && website.logo && data.logo !== website.logo) {
            deleteFile(website.logo);
        }
        if (data.favicon && website.favicon && data.favicon !== website.favicon) {
            deleteFile(website.favicon);
        }

        // Handle banner array update
        if (data.banner && website.banner && Array.isArray(website.banner)) {
            // website.banner is the old array
            // data.banner is the new array
            // Delete any image in old array that is NOT in new array
            website.banner.forEach((oldBanner) => {
                if (!data.banner.includes(oldBanner)) {
                    deleteFile(oldBanner);
                }
            });
        }

        return await websiteModel.findOneAndUpdate({ _id: website._id }, data, { new: true });
    }
}

module.exports = new WebsiteService();
