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

class Drug {
    static async create(drugData) {
        const { name, type } = drugData;

        const query = `
            INSERT INTO drugs (name, type)
            VALUES (?, ?)
        `;

        try {
            const [result] = await db.execute(query, [name, type || null]);
            return result.insertId;
        } catch (error) {
            throw error;
        }
    }

    static async findAll() {
        const query = `
            SELECT * FROM drugs 
            ORDER BY name ASC
        `;

        try {
            const [rows] = await db.execute(query);
            return rows;
        } catch (error) {
            throw error;
        }
    }

    static async findById(id) {
        const query = `SELECT * FROM drugs WHERE id = ?`;

        try {
            const [rows] = await db.execute(query, [id]);
            return rows.length > 0 ? rows[0] : null;
        } catch (error) {
            throw error;
        }
    }

    static async findByName(name) {
        const query = `SELECT * FROM drugs WHERE name = ?`;

        try {
            const [rows] = await db.execute(query, [name]);
            return rows.length > 0 ? rows[0] : null;
        } catch (error) {
            throw error;
        }
    }

    static async update(id, drugData) {
        const { name, type } = drugData;

        const query = `
            UPDATE drugs 
            SET name = ?, type = ?
            WHERE id = ?
        `;

        try {
            const [result] = await db.execute(query, [name, type || null, id]);
            return result.affectedRows > 0;
        } catch (error) {
            throw error;
        }
    }

    static async delete(id) {
        const query = `DELETE FROM drugs WHERE id = ?`;

        try {
            const [result] = await db.execute(query, [id]);
            return result.affectedRows > 0;
        } catch (error) {
            throw error;
        }
    }

    static async search(searchTerm) {
        const query = `
            SELECT * FROM drugs 
            WHERE name LIKE ? OR type LIKE ?
            ORDER BY name ASC
        `;

        try {
            const [rows] = await db.execute(query, [`%${searchTerm}%`, `%${searchTerm}%`]);
            return rows;
        } catch (error) {
            throw error;
        }
    }
}

module.exports = Drug;
