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

class DrugsAdministered {
    static async create(drugData) {
        const {
            patient_report_id,
            drug_id,
            dose,
            route,
            time_given
        } = drugData;

        const query = `
            INSERT INTO drugs_administered 
            (patient_report_id, drug_id, dose, route, time_given)
            VALUES (?, ?, ?, ?, ?)
        `;

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

    static async findByPatientReportId(patientReportId) {
        const query = `
            SELECT da.*, d.name as drug_name, d.type as drug_type
            FROM drugs_administered da
            JOIN drugs d ON da.drug_id = d.id
            WHERE da.patient_report_id = ?
            ORDER BY da.time_given DESC
        `;

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

    static async update(id, drugData) {
        const {
            drug_id,
            dose,
            route,
            time_given
        } = drugData;

        const query = `
            UPDATE drugs_administered 
            SET drug_id = ?, dose = ?, route = ?, time_given = ?
            WHERE id = ?
        `;

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

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

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

module.exports = DrugsAdministered;
