const db = require('../config/db');

class ItemService {
    async getAll() {
        const [rows] = await db.execute('SELECT * FROM items ORDER BY created_at DESC');
        return rows;
    }

    async getById(id) {
        const [rows] = await db.execute('SELECT * FROM items WHERE id = ?', [id]);
        return rows[0];
    }

    async create(itemData) {
        const { item_code, item_name, description, rental_rate, rate_type, status, quantity, remarks } = itemData;
        const [result] = await db.execute(
            'INSERT INTO items (item_code, item_name, description, rental_rate, rate_type, status, quantity, available_quantity, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [
                item_code || null,
                item_name || null,
                description || null,
                rental_rate || 0,
                rate_type || 'DAY',
                status || 'AVAILABLE',
                quantity || 1,
                quantity || 1,
                remarks || null
            ]
        );
        return { id: result.insertId, ...itemData };
    }

    async update(id, itemData) {
        const { item_code, item_name, description, rental_rate, rate_type, status, quantity, remarks } = itemData;
        await db.execute(
            'UPDATE items SET item_code = ?, item_name = ?, description = ?, rental_rate = ?, rate_type = ?, status = ?, quantity = ?, remarks = ? WHERE id = ?',
            [
                item_code || null,
                item_name || null,
                description || null,
                rental_rate || 0,
                rate_type || 'DAY',
                status || 'AVAILABLE',
                quantity || 1,
                remarks || null,
                id
            ]
        );
        return { id, ...itemData };
    }

    async updateStatus(id, status) {
        await db.execute('UPDATE items SET status = ? WHERE id = ?', [status, id]);
        return { id, status };
    }
}

module.exports = new ItemService();
