
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import path from 'path';
import Doctor from '../models/Doctor';
import User from '../models/User';

dotenv.config({ path: path.resolve(__dirname, '../../.env') });

const fixMissingDoctors = async () => {
    try {
        await mongoose.connect(process.env.MONGO_URI || process.env.MONGODB_URI || 'mongodb://localhost:27017/clinic-management');
        console.log('Connected to MongoDB');

        // Find all users with userType 'doctor' or 'dentist'
        const doctors = await User.find({ userType: { $in: ['doctor', 'dentist'] } });
        console.log(`Found ${doctors.length} users with userType 'doctor' or 'dentist'`);

        for (const user of doctors) {
            // Check if a Doctor record exists for this user
            const doctor = await Doctor.findOne({ userId: user._id });

            if (!doctor) {
                console.log(`Missing Doctor record for user: ${user.email} (${user._id})`);

                // Create the missing Doctor record
                const newDoctor = new Doctor({
                    userId: user._id,
                    isDentist: user.isDentist || false, // Use isDentist from User if available, default to false
                    createdAt: user.createdAt // Match creation time with user
                });

                await newDoctor.save();
                console.log(`Created Doctor record for user: ${user.email}`);
            } else {
                console.log(`Doctor record already exists for user: ${user.email}`);
            }
        }

        console.log('Finished checking and fixing missing doctors.');

    } catch (error) {
        console.error('Error:', error);
    } finally {
        await mongoose.disconnect();
    }
};

fixMissingDoctors();
