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 targetUserId = process.argv[2];

const run = async () => {
  if (!targetUserId) {
    throw new Error('Usage: ts-node src/scripts/fix-doctor-by-user-id.ts <userId>');
  }

  if (!mongoose.Types.ObjectId.isValid(targetUserId)) {
    throw new Error(`Invalid userId: ${targetUserId}`);
  }

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

  const user = await User.findById(targetUserId);
  if (!user) {
    throw new Error(`User not found: ${targetUserId}`);
  }

  if (user.userType !== 'doctor' && user.userType !== 'dentist') {
    throw new Error(`User ${targetUserId} is not doctor/dentist. Current type: ${user.userType}`);
  }

  const doctor = await Doctor.findOneAndUpdate(
    { userId: user._id },
    {
      $setOnInsert: {
        userId: user._id,
        isDentist: user.userType === 'dentist' || !!user.isDentist,
        createdAt: user.createdAt || new Date()
      }
    },
    { upsert: true, new: true }
  );

  console.log('Doctor record ensured:', {
    doctorId: doctor?._id,
    userId: user._id,
    email: user.email,
    userType: user.userType,
    isDentist: doctor?.isDentist,
  });
};

run()
  .catch((error: any) => {
    console.error('Error:', error.message || error);
    process.exitCode = 1;
  })
  .finally(async () => {
    try {
      await mongoose.disconnect();
    } catch {
      // ignore
    }
  });
