const queueManager = require('./backend/queueManager');
const botLogic = require('./backend/botLogic');
const configManager = require('./backend/configManager');

console.log("=== STARTING BACKEND UNIT TESTS ===");

// 1. Test QueueManager - Online Booking Limits
console.log("\nTesting QueueManager: Online Booking Limits");
const date = "2026-05-13";
const time = "10:00";

for (let i = 0; i < 4; i++) {
    const res = queueManager.bookOnline(date, time);
    console.log(`Booking ${i+1}:`, res.success ? `Success - ${res.token}` : `Failed - ${res.message}`);
}

// 2. Test QueueManager - Walkin Booking
console.log("\nTesting QueueManager: Walk-in Booking");
const walkRes = queueManager.bookWalkin(date, time);
console.log("Walkin result:", walkRes.token);

// 3. Test Bot Logic - WhatsApp Simulation
console.log("\nTesting BotLogic: WhatsApp Interactions");
async function testBot() {
    const msg1 = await botLogic.handleMessage("9876543210", "Hi");
    console.log("User: Hi -> Bot:", msg1.reply);

    const msg2 = await botLogic.handleMessage("9876543210", "Book Token");
    console.log("User: Book Token -> Bot:", msg2.reply);
    console.log("Buttons:", msg2.buttons);
}

testBot();

// 4. Test ConfigManager - Multi-tenancy
console.log("\nTesting ConfigManager: Multi-tenancy");
const sharmaConfig = configManager.getTenantConfig('sharma-clinic');
console.log("Sharma Clinic Name:", sharmaConfig.name);

// 5. Test Multi-tenant Booking
console.log("\nTesting Multi-tenant Booking (Sharma Clinic)");
const sharmaRes = queueManager.bookOnline(date, time, 'sharma-clinic');
console.log("Sharma Booking Result:", sharmaRes.success ? `Success - ${sharmaRes.token} (Fee: ${sharmaRes.fee})` : "Failed");

// 6. Test Scheduling Logic
console.log("\nTesting Scheduling Logic: Closed Hours");
const closedTime = "14:00"; // 2 PM is closed (1-5 PM break)
const closedRes = queueManager.bookOnline(date, closedTime);
console.log(`Booking at 2 PM (Closed):`, closedRes.success ? "Failed (Should be closed)" : `Success - ${closedRes.message}`);

console.log("\nTesting Scheduling Logic: Holidays");
const holidayDate = "2024-12-25"; // Christmas is a holiday in default config
const holidayRes = queueManager.bookOnline(holidayDate, "10:00");
console.log(`Booking on Christmas (Holiday):`, holidayRes.success ? "Failed (Should be holiday)" : `Success - ${holidayRes.message}`);

console.log("\nTesting Scheduling Logic: Days Off (Sunday)");
const sundayDate = "2026-05-17"; // May 17, 2026 is Sunday
const sundayRes = queueManager.bookOnline(sundayDate, "10:00");
console.log(`Booking on Sunday (Day Off):`, sundayRes.success ? "Failed (Should be off)" : `Success - ${sundayRes.message}`);

// 7. Test Cancellation & Reschedule Notification
console.log("\nTesting Cancellation & Reschedule Notification");
const cancelDate = "2026-05-13";
const cancelTime = "09:00";

// Ensure there is a booking to cancel
queueManager.bookOnline(cancelDate, cancelTime);
const cancelRes = queueManager.cancelBooking(cancelDate, cancelTime);
console.log("Cancel result:", cancelRes.message);

// 8. Test Reschedule Acceptance
console.log("\nTesting Reschedule Acceptance");
const patientPhone = "9876543210";
botLogic.setRescheduleOffer(patientPhone, {
    date: cancelDate,
    oldTime: "19:00",
    newTime: cancelTime
});
async function testReschedule() {
    const res = await botLogic.handleMessage(patientPhone, "1"); // User says "Yes" (1)
    console.log("User: 1 -> Bot:", res.reply);
}
testReschedule();

// 9. Test Future Booking Flow
console.log("\nTesting Future Booking Flow");
async function testFutureBooking() {
    const pId = "1234567890";
    const msg1 = await botLogic.handleMessage(pId, "Hi");
    const msg2 = await botLogic.handleMessage(pId, "English");
    const msg3 = await botLogic.handleMessage(pId, "Book for Future");
    console.log("User: Book for Future -> Bot:", msg3.reply);
    console.log("Date Options:", msg3.buttons);

    const selectedDate = msg3.buttons[0];
    const msg4 = await botLogic.handleMessage(pId, selectedDate);
    console.log(`User: ${selectedDate} -> Bot:`, msg4.reply);

    const msg5 = await botLogic.handleMessage(pId, "10:00 AM");
    console.log("User: 10:00 AM -> Bot:", msg5.reply);
}
testFutureBooking();

// 10. Test Family Profiles Flow
console.log("\nTesting Family Profiles Flow");
async function testFamilyProfiles() {
    const familyPhone = "9876543210"; // Has existing profiles in PatientManager mock
    const msg1 = await botLogic.handleMessage(familyPhone, "Hi");
    const msg2 = await botLogic.handleMessage(familyPhone, "English");
    console.log("User: English -> Bot:", msg2.reply);
    console.log("Profile Buttons:", msg2.buttons);

    const msg3 = await botLogic.handleMessage(familyPhone, "Suman Verma");
    console.log("User: Suman Verma -> Bot:", msg3.reply);
    
    // Test Adding New Member
    const newPhone = "9999988888"; // New number
    const reg1 = await botLogic.handleMessage(newPhone, "Hi");
    const reg2 = await botLogic.handleMessage(newPhone, "English");
    console.log("New User: English -> Bot:", reg2.reply);
    
    const reg3 = await botLogic.handleMessage(newPhone, "John Doe");
    console.log("New User: John Doe -> Bot:", reg3.reply);
    
    const reg4 = await botLogic.handleMessage(newPhone, "Book for Today");
    console.log("New User: Book for Today -> Bot:", reg4.reply);
}
testFamilyProfiles();

// 11. Test Agentic Pharmacy Flow
console.log("\nTesting Agentic Pharmacy Flow");
const pharmacyAgent = require('./backend/pharmacyAgent');
const pharmacyManager = require('./backend/pharmacyManager');

async function testPharmacyAgent() {
    // A. Test Patient Query
    const pId = "1234567890";
    const q1 = await botLogic.handleMessage(pId, "Do you have Paracetamol?");
    console.log("User: Do you have Paracetamol? -> Bot:", q1.reply);

    const q2 = await botLogic.handleMessage(pId, "Do you have Cough Syrup?");
    console.log("User: Do you have Cough Syrup? -> Bot:", q2.reply);

    // B. Test Autonomous Stock Scanning
    console.log("\n--- Triggering Autonomous Inventory Scan ---");
    // Manually set one item to very low stock
    const inventory = pharmacyManager.getInventory();
    inventory[0].stock = 2; // Paracetamol 500mg
    
    await pharmacyAgent.analyzeInventory();
    
    console.log("Waiting for autonomous restock simulation...");
    setTimeout(() => {
        console.log("Post-Restock Stock Level:", inventory[0].stock);
    }, 4000);

    // C. Test GST Billing
    console.log("\nTesting GST Billing Calculation");
    const bill = pharmacyManager.calculateBill('M04', 10); // Vitamin C (18% GST)
    console.log(`Item: ${bill.itemName} (HSN: ${bill.hsn})`);
    console.log(`Subtotal: ₹${bill.subtotal}, GST (${bill.gstRate}%): ₹${bill.gstAmount}, Total: ₹${bill.total}`);

    // D. Test Expiry Analysis
    console.log("\nTesting Autonomous Expiry Scan");
    pharmacyAgent.analyzeExpiries(pharmacyManager.getInventory());
}
testPharmacyAgent();
