const websiteService = require('../services/website.service');

const { OK } = require('../core/success.response');

class WebsiteController {
    async getWebsite(req, res) {
        const website = await websiteService.getWebsite();
        // Trả về init data rỗng nếu chưa cấu hình
        return new OK({
            message: 'success',
            metadata: website || {
                nameWebsite: '', logo: '', favicon: '',
                description: '', keywords: '', author: '',
                contact: '', social: '', status: 'active', banner: [],
            },
        }).send(res);
    }

    async topDeposit(req, res) {
        const data = await websiteService.topDeposit();
        return new OK({ message: 'success', metadata: data }).send(res);
    }

    async updateWebsite(req, res) {
        const { uploadSingle, uploadMultiple } = require('../config/cloudinaryUpload');
        const data = { ...req.body };

        if (req.files) {
            if (req.files['logo'] && req.files['logo'][0]) {
                data.logo = await uploadSingle(req.files['logo'][0], 'websites');
            }
            if (req.files['favicon'] && req.files['favicon'][0]) {
                data.favicon = await uploadSingle(req.files['favicon'][0], 'websites');
            }
        }

        // Handle banner (Array of strings)
        let bannerList = [];
        // Add existing banners (sent as text in body) - these are already Cloudinary URLs
        if (req.body.banner) {
            if (Array.isArray(req.body.banner)) {
                bannerList = [...req.body.banner];
            } else {
                bannerList.push(req.body.banner);
            }
        }
        // Add new uploaded banners to Cloudinary
        if (req.files && req.files['banner']) {
            const newBannerUrls = await uploadMultiple(req.files['banner'], 'websites');
            bannerList = [...bannerList, ...newBannerUrls];
        }

        if (req.body.banner !== undefined || (req.files && req.files['banner'])) {
            data.banner = bannerList;
        }

        const website = await websiteService.updateWebsite(data);
        return new OK({ message: 'success', metadata: website }).send(res);
    }
}

module.exports = new WebsiteController();
