/**
 * PharmacyManager: Handles inventory, prescriptions, and billing.
 */

class PharmacyManager {
    constructor() {
        this.inventory = [
            { id: 'M01', name: 'Paracetamol 500mg', stock: 120, price: 5, batch: 'B2201', expiry: '2026-12-30', hsn: '3004', gst: 12 },
            { id: 'M02', name: 'Amoxicillin 250mg', stock: 45, price: 12, batch: 'B2205', expiry: '2026-06-15', hsn: '3004', gst: 12 },
            { id: 'M03', name: 'Cough Syrup', stock: 104, price: 85, batch: 'S881', expiry: '2026-04-10', hsn: '3004', gst: 12 },
            { id: 'M04', name: 'Vitamin C', stock: 200, price: 3, batch: 'V009', expiry: '2027-01-01', hsn: '2936', gst: 18 },
            { id: 'M05', name: 'Azithromycin', stock: 30, price: 150, batch: 'A772', expiry: '2026-08-20', hsn: '3004', gst: 12 },
            { id: 'M06', name: 'Insulin Glargine', stock: 12, price: 450, batch: 'I110', expiry: '2026-05-25', hsn: '3004', gst: 5 }
        ];
        this.lowStockThreshold = 10;
        this.pendingOrders = [
            { id: 'ORD-901', patientName: 'Rahul Verma', medicines: 'Paracetamol, Cough Syrup', status: 'PENDING', timestamp: '2026-05-13T09:15:00Z' },
            { id: 'ORD-902', patientName: 'Anjali Singh', medicines: 'Amoxicillin', status: 'READY', timestamp: '2026-05-13T09:45:00Z' }
        ]; 
    }

    getInventory() {
        return this.inventory;
    }

    addPendingOrder(patientName, medicines) {
        this.pendingOrders.push({
            id: `ORD-${Date.now()}`,
            patientName,
            medicines,
            status: 'PENDING',
            timestamp: new Date().toISOString()
        });
    }

    processOrder(orderId) {
        const order = this.pendingOrders.find(o => o.id === orderId);
        if (order) {
            order.status = 'READY';
            // Deduct stock (simplified for now)
            const meds = order.medicines.split(', ');
            meds.forEach(m => this.deductStock(m, 1));
            return { success: true, message: `Order for ${order.patientName} is ready for pickup.` };
        }
        return { success: false, message: "Order not found." };
    }

    deductStock(medName, qty) {
        const med = this.inventory.find(i => i.name.includes(medName));
        if (med) {
            med.stock -= qty;
            if (med.stock < this.lowStockThreshold) {
                console.log(`[Pharmacy] ⚠️ ALERT: Low stock for ${med.name} (${med.stock} left)`);
                return { lowStock: true, medName: med.name };
            }
        }
        return { lowStock: false };
    }

    restock(medName, qty) {
        const med = this.inventory.find(i => i.name.includes(medName));
        if (med) {
            med.stock += qty;
            console.log(`[Pharmacy] ✅ Restocked ${med.name}. New stock: ${med.stock}`);
        }
    }

    calculateBill(medId, qty) {
        const item = this.inventory.find(i => i.id === medId);
        if (!item) return null;

        const subtotal = item.price * qty;
        const gstAmount = (subtotal * item.gst) / 100;
        const total = subtotal + gstAmount;

        return {
            itemName: item.name,
            qty,
            rate: item.price,
            subtotal,
            gstRate: item.gst,
            gstAmount,
            total,
            hsn: item.hsn
        };
    }

    fulfillPrescription(prescription) {
        console.log(`[Pharmacy] Fulfilling Rx: ${prescription.id} for Patient ${prescription.patientId}`);
        
        const billItems = [];
        let totalBill = 0;

        prescription.medicines.forEach(m => {
            const med = this.inventory.find(i => i.name.toLowerCase().includes(m.name.toLowerCase()));
            if (med) {
                const itemBill = this.calculateBill(med.id, m.qty || 10);
                billItems.push(itemBill);
                totalBill += itemBill.total;
                this.deductStock(med.name, m.qty || 10);
            }
        });

        // Forward Lab Tests
        if (prescription.labTests && prescription.labTests.length > 0) {
            this.forwardToLab(prescription.patientId, prescription.labTests);
        }

        return {
            billItems,
            totalBill,
            labStatus: prescription.labTests.length > 0 ? "FORWARDED" : "NONE"
        };
    }

    forwardToLab(patientId, tests) {
        console.log(`[Pharmacy] 🔬 AUTONOMOUS ACTION: Forwarding ${tests.length} tests to Lab for Patient ${patientId}`);
        tests.forEach(t => {
            console.log(`[Lab] 📥 Received Request: ${t.testName} for Patient ${patientId}`);
        });
    }
}

module.exports = new PharmacyManager();
