const { getDatabase } = require('../config/database');

const StockThreshold = {
    getAll() {
        const db = getDatabase();
        return db.prepare(`SELECT * FROM stock_thresholds ORDER BY category`).all();
    },

    getByCategory(category) {
        const db = getDatabase();
        return db.prepare(`SELECT * FROM stock_thresholds WHERE category = ?`).get(category);
    },

    upsert(data) {
        const db = getDatabase();
        db.prepare(`
            INSERT INTO stock_thresholds (category, min_stock, notify_email, updated_at)
            VALUES (@category, @min_stock, @notify_email, CURRENT_TIMESTAMP)
            ON CONFLICT(category) DO UPDATE SET
                min_stock = excluded.min_stock,
                notify_email = excluded.notify_email,
                updated_at = CURRENT_TIMESTAMP
        `).run({
            category:     data.category,
            min_stock:    data.min_stock || 1,
            notify_email: data.notify_email || null,
        });
        return this.getByCategory(data.category);
    },

    delete(category) {
        const db = getDatabase();
        return db.prepare(`DELETE FROM stock_thresholds WHERE category = ?`).run(category).changes > 0;
    },

    // Returns categories where current count <= min_stock
    getViolations() {
        const db = getDatabase();
        return db.prepare(`
            SELECT
                t.category,
                t.min_stock,
                t.notify_email,
                COUNT(a.id) AS current_stock
            FROM stock_thresholds t
            LEFT JOIN assets a ON a.type = t.category AND a.status = 'verfuegbar'
            GROUP BY t.category
            HAVING current_stock <= t.min_stock
            ORDER BY current_stock ASC
        `).all();
    },
};

module.exports = StockThreshold;
