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

class FluidsAdministered {
    static async create(fluidData) {
        const {
            patient_report_id,
            fluid_name,
            volume,
            time_given
        } = fluidData;

        const query = `
            INSERT INTO fluids_administered 
            (patient_report_id, fluid_name, volume, time_given)
            VALUES (?, ?, ?, ?)
        `;

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

    static async findByPatientReportId(patientReportId) {
        const query = `
            SELECT * FROM fluids_administered 
            WHERE patient_report_id = ?
            ORDER BY time_given DESC
        `;

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

    static async update(id, fluidData) {
        const {
            fluid_name,
            volume,
            time_given
        } = fluidData;

        const query = `
            UPDATE fluids_administered 
            SET fluid_name = ?, volume = ?, time_given = ?
            WHERE id = ?
        `;

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

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

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

module.exports = FluidsAdministered;
