const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const { requireAdmin } = require('../middleware/roleCheck');
const { asyncHandler } = require('../middleware/errorHandler');
const Database = require('better-sqlite3');
const DB_PATH = process.env.DATABASE_PATH || './database.sqlite';

router.use(authenticateToken);

// GET alle Preise
router.get('/', asyncHandler(async (req, res) => {
    const db = new Database(DB_PATH);
    const prices = db.prepare('SELECT * FROM license_prices ORDER BY display_name').all();
    db.close();
    res.json({ status: 'success', data: prices });
}));

// PUT Preis aktualisieren
router.put('/:id', requireAdmin, asyncHandler(async (req, res) => {
    const { price_per_month, display_name } = req.body;
    const db = new Database(DB_PATH);
    db.prepare('UPDATE license_prices SET price_per_month=?, display_name=?, updated_at=CURRENT_TIMESTAMP WHERE id=?')
        .run(parseFloat(price_per_month) || 0, display_name, parseInt(req.params.id));
    const updated = db.prepare('SELECT * FROM license_prices WHERE id=?').get(parseInt(req.params.id));
    db.close();
    res.json({ status: 'success', data: updated });
}));

// POST neuer Preis
router.post('/', requireAdmin, asyncHandler(async (req, res) => {
    const { sku_part_number, display_name, price_per_month } = req.body;
    const db = new Database(DB_PATH);
    const result = db.prepare('INSERT OR REPLACE INTO license_prices (sku_part_number, display_name, price_per_month) VALUES (?,?,?)')
        .run(sku_part_number, display_name, parseFloat(price_per_month) || 0);
    const created = db.prepare('SELECT * FROM license_prices WHERE id=?').get(result.lastInsertRowid);
    db.close();
    res.json({ status: 'success', data: created });
}));

// DELETE
router.delete('/:id', requireAdmin, asyncHandler(async (req, res) => {
    const db = new Database(DB_PATH);
    db.prepare('DELETE FROM license_prices WHERE id=?').run(parseInt(req.params.id));
    db.close();
    res.json({ status: 'success' });
}));

module.exports = router;
