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

const Campaign = require("../models/Campaign");
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 notes = await Note.find({ campaign })
            .select('_id title content date campaign')
            .sort({ date: -1 })
            .lean();

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

router.post('/create', async (req, res) => {
    try {
        const { title, content, campaign } = req.body;
        const hasAccess = await userOwnsCampaign(campaign, req.user.id);
        if (!hasAccess) return res.json({ status: "error", msg: "unauthorized" });

        const newNote = new Note({
            title,
            content,
            campaign
        });
        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 } = req.body;
        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) note.title = title;
        note.content = content;
        note.date = Date.now();
        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;
        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" });

        await note.remove();
        res.json({ status: "ok" });
    } catch (err) {
        console.error(err);
        res.json({ status: "error", msg: "errors.internal" });
    }
});

module.exports = router;
