import crypto from 'crypto';
import * as dotenv from 'dotenv';
import fs from 'fs';
import mongoose from 'mongoose';
import path from 'path';
import Doctor from '../../models/Doctor';
import User from '../../models/User';

// Load environment variables
dotenv.config({ path: path.join(__dirname, '../../../.env') });

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

async function seedDoctors() {
    try {
        console.log('='.repeat(50));
        console.log('MONGODB_URI:', MONGODB_URI);
        console.log('='.repeat(50));
        console.log('Connecting to MongoDB...', MONGODB_URI);
        await mongoose.connect(MONGODB_URI);
        console.log('Connected to MongoDB.');

        const dataPath = path.join(__dirname, '../../../data/doctors.json');
        if (!fs.existsSync(dataPath)) {
            console.error('Data file not found:', dataPath);
            process.exit(1);
        }

        // Clear existing doctors and their users
        console.log('Clearing existing doctors...');
        await Doctor.deleteMany({});
        await User.deleteMany({ userType: 'doctor' });
        
        // Drop old indexes
        try {
            await Doctor.collection.dropIndex('email_1');
            console.log('Dropped email index from doctors collection.');
        } catch (err: any) {
            if (err.code !== 27) { // 27 means index doesn't exist
                console.log('No email index to drop.');
            }
        }
        
        console.log('Cleared existing doctors and doctor users.');

        const doctorsData = JSON.parse(fs.readFileSync(dataPath, 'utf-8'));
        console.log(`Found ${doctorsData.length} doctors to seed.`);

        let createdCount = 0;
        let skippedCount = 0;

        for (const data of doctorsData) {
            const { firstName, lastName, email, phone, isDentist, licenseNumber } = data;

            // Check if user exists
            const normalizedEmail = email.toLowerCase();
            let user = await User.findOne({ email: normalizedEmail });

            if (!user) {
                const password = crypto.randomBytes(8).toString('hex');
                user = await User.create({
                    firstName,
                    lastName,
                    email,
                    password,
                    userType: 'doctor',
                    phone,
                    isActive: true
                });
                console.log(`Created user: ${email}`);
            } else {
                console.log(`User already exists: ${email}`);
            }

            // Check if doctor profile exists
            const existingDoctor = await Doctor.findOne({ userId: user._id });
            if (!existingDoctor) {
                await Doctor.create({
                    userId: user._id,
                    isDentist: isDentist || false,
                    licenseNumber
                });
                console.log(`Created doctor profile for: ${firstName} ${lastName} (${isDentist ? 'Dentist' : 'Doctor'})`);
                createdCount++;
            } else {
                console.log(`Doctor profile already exists for: ${firstName} ${lastName}`);
                skippedCount++;
            }
        }

        console.log('\n=== Seeding Complete ===');
        console.log(`Created: ${createdCount}`);
        console.log(`Skipped: ${skippedCount}`);

    } catch (error) {
        console.error('Error seeding doctors:', error);
    } finally {
        await mongoose.disconnect();
        console.log('Disconnected from MongoDB.');
        process.exit(0);
    }
}

seedDoctors();
