const ItTopic = require('../models/ItTopic');
const { syncItTopicsToPlanner } = require('../services/graph.service');

exports.getAll = (req, res) => {
    const { category, status } = req.query;
    const data = ItTopic.getAll({ category, status });
    res.json({ status: 'success', data });
};

exports.getOne = (req, res) => {
    const topic = ItTopic.getById(req.params.id);
    if (!topic) return res.status(404).json({ status: 'error', message: 'Thema nicht gefunden' });
    res.json({ status: 'success', data: topic });
};

exports.create = (req, res) => {
    const { title, category, status, priority, responsible, target_date, description, notes } = req.body;
    if (!title?.trim()) {
        return res.status(400).json({ status: 'error', message: 'Titel ist erforderlich' });
    }
    const topic = ItTopic.create({ title: title.trim(), category, status, priority, responsible, target_date, description, notes });
    res.status(201).json({ status: 'success', data: topic });
};

exports.update = (req, res) => {
    const topic = ItTopic.getById(req.params.id);
    if (!topic) return res.status(404).json({ status: 'error', message: 'Thema nicht gefunden' });
    const { title, category, status, priority, responsible, target_date, description, notes, sort_order } = req.body;
    const updated = ItTopic.update(req.params.id, { title, category, status, priority, responsible, target_date, description, notes, sort_order });
    res.json({ status: 'success', data: updated });
};

exports.remove = (req, res) => {
    const ok = ItTopic.delete(req.params.id);
    if (!ok) return res.status(404).json({ status: 'error', message: 'Thema nicht gefunden' });
    res.json({ status: 'success', message: 'Thema gelöscht' });
};

exports.syncToPlanner = async (req, res) => {
    const planId = process.env.PLANNER_PLAN_ID;
    if (!planId) return res.status(400).json({ status: 'error', message: 'PLANNER_PLAN_ID nicht konfiguriert' });
    const topics = ItTopic.getAll({});
    const result = await syncItTopicsToPlanner(topics, planId);
    res.json({ status: 'success', data: result });
};
