const express = require('express');
const router = express.Router();

const Campaign = require('../models/Campaign');
const Folder = require('../models/Folder');
const Note = require('../models/Note');

async function userOwnsCampaign(campaignId, userId) {
    const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
    return Boolean(campaign);
}

router.get('/list', async (req, res) => {
    try {
        const { campaign } = req.query;
        if (!campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });

        const hasAccess = await userOwnsCampaign(campaign, req.user.id);
        if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });

        const folders = await Folder.find({ campaign })
            .select('_id name date')
            .sort({ date: -1 })
            .lean();

        res.json({ status: 'ok', folders });
    } catch (err) {
        console.error(err);
        res.json({ status: 'error', msg: 'errors.internal' });
    }
});

router.post('/create', async (req, res) => {
    try {
        const { name, campaign } = req.body;
        if (!name || !campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });

        const hasAccess = await userOwnsCampaign(campaign, req.user.id);
        if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });

        const newFolder = new Folder({
            name: name.trim(),
            campaign
        });
        await newFolder.save();
        res.json({ status: 'ok', folder: newFolder });
    } catch (err) {
        console.error(err);
        res.json({ status: 'error', msg: 'errors.internal' });
    }
});

router.post('/delete', async (req, res) => {
    try {
        const { id } = req.body;
        if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });

        const folder = await Folder.findById(id);
        if (!folder) return res.json({ status: 'error', msg: 'errors.notfound' });

        const hasAccess = await userOwnsCampaign(folder.campaign, req.user.id);
        if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });

        async function moveRecursive(folderId) {
            const subfolders = await Folder.find({ parentFolder: folderId }).select('_id').lean();
            await Note.updateMany(
                { folder: folderId },
                { $set: { folder: null, date: Date.now() } }
            );
            await Folder.deleteOne({ _id: folderId });
            for (const sub of subfolders) {
                await moveRecursive(sub._id);
            }
        }

        await moveRecursive(id);

        res.json({ status: 'ok' });
    } catch (err) {
        console.error(err);
        res.json({ status: 'error', msg: 'errors.internal' });
    }
});

router.post('/rename', async (req, res) => {
    try {
        const { id, name } = req.body;
        if (!id || !name) return res.json({ status: 'error', msg: 'errors.missing-data' });

        const folder = await Folder.findById(id);
        if (!folder) return res.json({ status: 'error', msg: 'errors.notfound' });

        const hasAccess = await userOwnsCampaign(folder.campaign, req.user.id);
        if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });

        folder.name = name.trim();
        await folder.save();

        res.json({ status: 'ok', folder });
    } catch (err) {
        console.error(err);
        res.json({ status: 'error', msg: 'errors.internal' });
    }
});

module.exports = router;
