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

const getAll = (req, res) => {
    const db = getDatabase();
    const rows = db.prepare('SELECT * FROM asset_types ORDER BY sort_order, name').all();
    res.json(rows);
};

const create = (req, res) => {
    const { name, icon = 'devices_other' } = req.body;
    if (!name?.trim()) return res.status(400).json({ error: 'Name erforderlich' });
    const db = getDatabase();
    const maxOrder = db.prepare('SELECT MAX(sort_order) as m FROM asset_types').get();
    try {
        const result = db.prepare(
            'INSERT INTO asset_types (name, icon, sort_order) VALUES (?, ?, ?)'
        ).run(name.trim(), icon, (maxOrder.m || 0) + 1);
        const row = db.prepare('SELECT * FROM asset_types WHERE id = ?').get(result.lastInsertRowid);
        res.status(201).json(row);
    } catch (e) {
        if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'Typ existiert bereits' });
        throw e;
    }
};

const update = (req, res) => {
    const db = getDatabase();
    const { name, icon } = req.body;
    const existing = db.prepare('SELECT * FROM asset_types WHERE id = ?').get(req.params.id);
    if (!existing) return res.status(404).json({ error: 'Nicht gefunden' });
    try {
        db.prepare('UPDATE asset_types SET name = ?, icon = ? WHERE id = ?')
            .run(name?.trim() ?? existing.name, icon ?? existing.icon, req.params.id);
        res.json(db.prepare('SELECT * FROM asset_types WHERE id = ?').get(req.params.id));
    } catch (e) {
        if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'Typ existiert bereits' });
        throw e;
    }
};

const remove = (req, res) => {
    const db = getDatabase();
    const existing = db.prepare('SELECT * FROM asset_types WHERE id = ?').get(req.params.id);
    if (!existing) return res.status(404).json({ error: 'Nicht gefunden' });
    db.prepare('DELETE FROM asset_types WHERE id = ?').run(req.params.id);
    res.json({ success: true });
};

module.exports = { getAll, create, update, remove };
