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

class Observation {
    static async create(observationData) {
        const {
            patient_report_id,
            observation,
            value
        } = observationData;

        const query = `
            INSERT INTO observations 
            (patient_report_id, observation, value)
            VALUES (?, ?, ?)
        `;

        try {
            const [result] = await db.execute(query, [
                patient_report_id,
                observation,
                value
            ]);
            return result.insertId;
        } catch (error) {
            throw error;
        }
    }

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

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

    static async update(id, observationData) {
        const {
            observation,
            value
        } = observationData;

        const query = `
            UPDATE observations 
            SET observation = ?, value = ?
            WHERE id = ?
        `;

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

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

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

    static getObservationTypes() {
        return [
            'Blood Pressure',
            'Pulse',
            'Temperature',
            'Respirations',
            'Oxygen Saturation',
            'Skin',
            'Dextrostix',
            'Pupils',
            'Glasgow Coma Scale',
            'Oxygen'
        ];
    }

    static async getLatestByType(patientReportId, observationType) {
        const query = `
            SELECT * FROM observations 
            WHERE patient_report_id = ? AND observation = ?
            ORDER BY created_at DESC
            LIMIT 1
        `;

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

module.exports = Observation;
