/**
 * PrescriptionManager: Handles digital prescription generation and storage in PostgreSQL.
 */
const db = require('./db');

class PrescriptionManager {
    /**
     * Create a new prescription
     */
    async generate(tenantId, doctorId, patientId, patientName, diagnosis, medicines = [], labTests = []) {
        const id = `RX-${Date.now()}`;
        const query = `
            INSERT INTO prescriptions (id, tenant_id, doctor_id, patient_id, patient_name, diagnosis, medicines, lab_tests, status)
            VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, 'pending')
            RETURNING *;
        `;
        const values = [
            id, tenantId, doctorId, patientId, patientName, diagnosis,
            JSON.stringify(medicines), JSON.stringify(labTests)
        ];

        const res = await db.query(query, values);
        const prescription = res.rows[0];

        // Ensure we format it properly for the whatsapp message
        const whatsappMessage = `💊 *Digital Prescription from Curio*\n\n*Patient:* ${patientName}\n*Diagnosis:* ${diagnosis}\n\n*Medicines:*\n${medicines.map(m => `- ${m.name}: ${m.dosage} (${m.frequency}) for ${m.duration}`).join('\n')}\n\n` +
                                (labTests.length > 0 ? `🔬 *Lab Tests Recommended:*\n${labTests.map(t => `- ${t.testName}`).join('\n')}\n\n` : "") +
                                `_You can show this message at our pharmacy for a 10% discount._`;

        return {
            success: true,
            prescriptionId: id,
            data: prescription,
            whatsappMessage
        };
    }

    /**
     * Get pending prescriptions for a tenant (used by Pharmacy)
     */
    async getPending(tenantId) {
        const query = `
            SELECT p.*, u.name as doctor_name 
            FROM prescriptions p
            LEFT JOIN users u ON p.doctor_id = u.id
            WHERE p.tenant_id = $1 AND p.status = 'pending'
            ORDER BY p.created_at ASC;
        `;
        const res = await db.query(query, [tenantId]);
        return res.rows;
    }

    /**
     * Update prescription status
     */
    async updateStatus(tenantId, id, status) {
        const query = `
            UPDATE prescriptions
            SET status = $1
            WHERE id = $2 AND tenant_id = $3
            RETURNING *;
        `;
        const res = await db.query(query, [status, id, tenantId]);
        return res.rows.length > 0 ? res.rows[0] : null;
    }
}

module.exports = new PrescriptionManager();
