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

const Campaign = require("../models/Campaign");

router.post('/create', async (req, res) => {
    try {
        const { name, description, color, settings } = req.body;
        const newCampaign = new Campaign({
            name,
            description,
            color,
            settings,
            createdBy: req.user.id
        });
        await newCampaign.save();
        res.json({ status: "ok", campaign: newCampaign });
    } catch (err) {
        console.error(err);
        res.json({ status: "error", msg: "errors.internal" });
    }
});

router.get('/list', async (req, res) => {
    try {
        const campaigns = await Campaign.find({ createdBy: req.user.id });
        res.json({ status: "ok", campaigns });
    } catch (err) {
        res.json({ status: "error", msg: "errors.internal", err });
    }
});

router.get('/retrieve/:id', async (req, res) => {
    try {
        if (!req.user?.id) return res.status(401).json({ status: "error", msg: "errors.unauthorized" });

        const campaign = await Campaign.findOne({ _id: req.params.id, createdBy: req.user.id });
        if (!campaign) return res.json({ status: "error", msg: "errors.not-found" });

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

module.exports = router;
