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

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

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();

        const rootNotes = await Note.find({ campaign, folder: null })
            .select('_id title content date')
            .sort({ date: -1 })
            .lean();

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

router.get('/subfolder/list', async (req, res) => {
    try {
        const { campaign, folder } = req.query;
        if (!campaign || !folder) 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' });

        // Verify folder belongs to campaign
        const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean();
        if (!folderDoc) return res.json({ status: 'error', msg: 'errors.notfound' });

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

        const notes = await Note.find({ campaign, folder: folder })
            .select('_id title content date')
            .sort({ date: -1 })
            .lean();

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

router.post('/create', async (req, res) => {
    try {
        const { title, content, campaign, folder } = req.body;
        if (!title || !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' });

        let effectiveFolder = null;
        if (folder) {
            const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean();
            if (!folderDoc) return res.json({ status: 'error', msg: 'errors.notfound' });
            effectiveFolder = folder;
        }

        const newNote = new Note({ title, content, campaign, folder: effectiveFolder });
        await newNote.save();
        res.json({ status: 'ok', note: newNote });
    } catch (err) {
        console.error(err);
        res.json({ status: 'error', msg: 'errors.internal' });
    }
});

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

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

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

        if (title !== undefined) note.title = title;
        if (content !== undefined) note.content = content;
        if (folder !== undefined) note.folder = folder;
        await note.save();
        res.json({ status: 'ok', note });
    } 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 result = await Note.deleteOne({ _id: id });
        if (result.deletedCount === 0) return res.json({ status: 'error', msg: 'errors.notfound' });

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

module.exports = router;
