/**
 * PharmacyAgent: An autonomous agent that manages hospital inventory
 * and interacts with vendors and patients.
 */

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

class PharmacyAgent {
    constructor() {
        this.vendorContact = "+91-9998887776 (Global Pharma)";
    }

    async analyzeInventory() {
        console.log("[PharmacyAgent] Scanning inventory for discrepancies...");
        const inventory = pharmacyManager.getInventory();
        const lowStockItems = inventory.filter(item => item.stock < 10);

        if (lowStockItems.length > 0) {
            console.log(`[PharmacyAgent] Found ${lowStockItems.length} items needing attention.`);
            for (const item of lowStockItems) {
                await this.placeOrder(item.name, 100);
            }
        }
        this.analyzeExpiries(inventory);
    }

    analyzeExpiries(inventory) {
        const today = new Date();
        const ninetyDaysOut = new Date();
        ninetyDaysOut.setDate(today.getDate() + 90);

        const nearingExpiry = inventory.filter(item => {
            const exp = new Date(item.expiry);
            return exp > today && exp < ninetyDaysOut;
        });

        if (nearingExpiry.length > 0) {
            console.log(`[PharmacyAgent] 🚨 EXPIRY ALERT: ${nearingExpiry.length} items expiring within 90 days.`);
            nearingExpiry.forEach(item => {
                console.log(`[PharmacyAgent] Suggestion: Run a 'Clearance Sale' or push ${item.name} (Batch: ${item.batch}) to front counter.`);
            });
        }
    }

    async placeOrder(medName, qty) {
        console.log(`[PharmacyAgent] 🤖 AUTONOMOUS ACTION: Sending WhatsApp to Vendor ${this.vendorContact}`);
        console.log(`[WhatsApp to Vendor]: "Urgent Order from Curio Health: Need ${qty} units of ${medName}. Please confirm delivery."`);
        
        // Mocking vendor response and auto-restock after 2 seconds
        setTimeout(() => {
            console.log(`[PharmacyAgent] 🚚 Vendor confirmed delivery for ${medName}.`);
            pharmacyManager.restock(medName, qty);
        }, 3000);
    }

    handlePatientQuery(query) {
        const text = query.toLowerCase();
        const inventory = pharmacyManager.getInventory();
        const found = inventory.find(i => text.includes(i.name.toLowerCase()));

        if (found) {
            if (found.stock > 0) {
                return `Yes, we have ${found.name} in stock. It costs ₹${found.price} per unit. Would you like me to reserve some for your visit?`;
            } else {
                return `I'm sorry, ${found.name} is currently out of stock. I've already notified our supplier, and it should be back in 2-3 days. Can I suggest an alternative?`;
            }
        }
        return "I'm not sure if we carry that specific medication. Let me check with our pharmacist and get back to you.";
    }
}

module.exports = new PharmacyAgent();
