const subscriptionService = require('../services/subscriptionService');

exports.createSubscription = async (req, res) => {
    try {
        const sub = await subscriptionService.createSubscription(req.body, req.user.id);
        res.status(201).json(sub);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.createFromInvoice = async (req, res) => {
    try {
        const sub = await subscriptionService.createSubscriptionFromInvoice(req.params.invoiceId, req.body, req.user.id);
        res.status(201).json(sub);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.getSubscriptions = async (req, res) => {
    try {
        const subs = await subscriptionService.getAllSubscriptions();
        res.json(subs);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.updateSubscription = async (req, res) => {
    try {
        const sub = await subscriptionService.updateSubscription(req.params.id, req.body, req.user.id);
        res.json(sub);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.deleteSubscription = async (req, res) => {
    try {
        await subscriptionService.deleteSubscription(req.params.id, req.user.id);
        res.json({ message: 'Subscription deleted' });
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.getSubscription = async (req, res) => {
    try {
        const sub = await subscriptionService.getSubscriptionById(req.params.id);
        if (!sub) return res.status(404).json({ message: 'Not found' });
        res.json(sub);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.runScheduler = async (req, res) => {
    try {
        const processed = await subscriptionService.processRecurringInvoices();
        res.json({ message: 'Scheduler completed', processed });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
