
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 Patient from '../../models/Patient';
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 seedData() {
    try {
        console.log('Connecting to MongoDB...', MONGODB_URI);
        await mongoose.connect(MONGODB_URI);
        console.log('Connected to MongoDB.');

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

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

        // Fetch all available doctors
        const doctors = await Doctor.find();
        if (doctors.length === 0) {
            console.error('No doctors found in database. Please seed doctors first.');
            process.exit(1);
        }
        console.log(`Found ${doctors.length} doctors available for assignment.`);

        let createdCount = 0;
        let skippedCount = 0;
        let doctorIndex = 0; // For round-robin assignment

        for (const data of patientsData) {
            const { firstName, lastName, email, phone, gender, dateOfBirth, address, medicalHistory, doctorId } = 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, // Random password, in real app would be hashed but User model handles hashing usually? 
                    // Wait, User model likely hashes in pre-save hook.
                    userType: 'patient',
                    phone,
                    isActive: true
                });
                console.log(`Created user: ${email}`);
            } else {
                console.log(`User already exists: ${email}`);
            }

            // Check if patient profile exists
            const existingPatient = await Patient.findOne({ userId: user._id });
            if (!existingPatient) {
                // Assign doctorId from data if provided, otherwise use round-robin
                let assignedDoctorId = doctorId;
                if (!assignedDoctorId) {
                    assignedDoctorId = doctors[doctorIndex % doctors.length]._id;
                    doctorIndex++;
                }

                await Patient.create({
                    userId: user._id,
                    doctorId: assignedDoctorId, // Assign doctor - REQUIRED
                    gender,
                    dateOfBirth: new Date(dateOfBirth),
                    address,
                    medicalHistory
                });
                console.log(`Created patient profile for: ${firstName} ${lastName} (Doctor ID: ${assignedDoctorId})`);
                createdCount++;
            } else {
                console.log(`Patient profile already exists for: ${firstName} ${lastName}`);
                skippedCount++;
            }
        }

        console.log('Seeding complete.');
        console.log(`Created: ${createdCount}`);
        console.log(`Skipped: ${skippedCount}`);

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

seedData();
