import 'dotenv/config';
import mongoose from 'mongoose';
import Appointment from '../models/Appointment';
import Patient from '../models/Patient';
import Prescription from '../models/Prescription';

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/clinic-management';

async function verifyDashboardStats() {
    try {
        await mongoose.connect(MONGODB_URI);
        console.log('Connected to MongoDB');

        // 1. Total Patients
        const totalPatients = await Patient.countDocuments();
        console.log(`Total Patients: ${totalPatients}`);

        // 2. Appointments this month
        const startOfMonth = new Date();
        startOfMonth.setDate(1);
        startOfMonth.setHours(0, 0, 0, 0);

        const endOfMonth = new Date(startOfMonth);
        endOfMonth.setMonth(endOfMonth.getMonth() + 1);

        const appointmentsThisMonth = await Appointment.countDocuments({
            appointmentDate: {
                $gte: startOfMonth,
                $lt: endOfMonth
            }
        });
        console.log(`Appointments This Month: ${appointmentsThisMonth}`);

        // 3. Total Prescriptions
        const totalPrescriptions = await Prescription.countDocuments();
        console.log(`Total Prescriptions: ${totalPrescriptions}`);

        // 4. Growth (New Patients This Month vs Last Month)
        const newPatientsThisMonth = await Patient.countDocuments({
            createdAt: {
                $gte: startOfMonth,
                $lt: endOfMonth
            }
        });

        const startOfLastMonth = new Date(startOfMonth);
        startOfLastMonth.setMonth(startOfLastMonth.getMonth() - 1);

        const endOfLastMonth = new Date(startOfMonth);

        const newPatientsLastMonth = await Patient.countDocuments({
            createdAt: {
                $gte: startOfLastMonth,
                $lt: endOfLastMonth
            }
        });

        let growth = 0;
        if (newPatientsLastMonth === 0) {
            growth = newPatientsThisMonth > 0 ? 100 : 0;
        } else {
            growth = ((newPatientsThisMonth - newPatientsLastMonth) / newPatientsLastMonth) * 100;
        }
        console.log(`New Patients This Month: ${newPatientsThisMonth}`);
        console.log(`New Patients Last Month: ${newPatientsLastMonth}`);
        console.log(`Growth: ${growth.toFixed(1)}%`);

        await mongoose.disconnect();
    } catch (error) {
        console.error('Error verifying stats:', error);
        process.exit(1);
    }
}

verifyDashboardStats();
