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

const PurchaseOrder = {
    getAll({ status } = {}) {
        const db = getDatabase();
        let q = `
            SELECT p.*, u.first_name || ' ' || u.last_name AS created_by_name
            FROM purchase_orders p
            LEFT JOIN users u ON p.created_by = u.id
        `;
        const params = [];
        if (status) { q += ` WHERE p.status = ?`; params.push(status); }
        q += ` ORDER BY p.created_at DESC`;
        return db.prepare(q).all(...params);
    },

    getById(id) {
        const db = getDatabase();
        return db.prepare(`
            SELECT p.*, u.first_name || ' ' || u.last_name AS created_by_name
            FROM purchase_orders p
            LEFT JOIN users u ON p.created_by = u.id
            WHERE p.id = ?
        `).get(id);
    },

    create(data) {
        const db = getDatabase();
        const result = db.prepare(`
            INSERT INTO purchase_orders (category, item_name, quantity, status, notes, created_by)
            VALUES (@category, @item_name, @quantity, @status, @notes, @created_by)
        `).run({
            category:  data.category,
            item_name: data.item_name,
            quantity:  data.quantity || 1,
            status:    data.status || 'offen',
            notes:     data.notes || '',
            created_by: data.created_by,
        });
        return this.getById(result.lastInsertRowid);
    },

    update(id, data) {
        const db = getDatabase();
        const fields = [];
        const params = {};

        if (data.status !== undefined) {
            fields.push(`status = @status`);
            params.status = data.status;
            if (data.status === 'bestellt') {
                fields.push(`ordered_at = CURRENT_TIMESTAMP`);
            } else if (data.status === 'erledigt') {
                fields.push(`completed_at = CURRENT_TIMESTAMP`);
            }
        }
        if (data.notes     !== undefined) { fields.push(`notes = @notes`);         params.notes     = data.notes; }
        if (data.quantity  !== undefined) { fields.push(`quantity = @quantity`);    params.quantity  = data.quantity; }
        if (data.item_name !== undefined) { fields.push(`item_name = @item_name`);  params.item_name = data.item_name; }

        fields.push(`updated_at = CURRENT_TIMESTAMP`);
        params.id = id;

        db.prepare(`UPDATE purchase_orders SET ${fields.join(', ')} WHERE id = @id`).run(params);
        return this.getById(id);
    },

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

    getOpenCount() {
        const db = getDatabase();
        return db.prepare(`SELECT COUNT(*) AS count FROM purchase_orders WHERE status = 'offen'`).get().count;
    },
};

module.exports = PurchaseOrder;
