import mongoose from 'mongoose';
import connectDB from '../src/lib/mongodb';
import UserType from '../src/models/UserType';
import User from '../src/models/User';
import State from '../src/models/State';
import Inquiry from '../src/models/Inquiry';

async function seed() {
  try {
    console.log('🌱 Starting database seeding...');
    const conn = await connectDB();
    console.log('✅ Connected to MongoDB:', conn.connection.host);

    // Create user types
    console.log('📝 Creating user types...');
    const adminType = await UserType.findOneAndUpdate(
      { role: 'admin' },
      { role: 'admin', roleId: 1 },
      { upsert: true, returnDocument: 'after' }
    );

    const userType = await UserType.findOneAndUpdate(
      { role: 'user' },
      { role: 'user', roleId: 2 },
      { upsert: true, returnDocument: 'after' }
    );

    console.log('✅ User types created - Admin ID:', adminType?._id, 'User ID:', userType?._id);

    // Create admin user
    console.log('👤 Creating admin user...');
    const adminUser = await User.findOneAndUpdate(
      { email: 'admin@gmail.com' },
      {
        name: 'Admin User',
        email: 'admin@gmail.com',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: adminType?._id,
        status: 'active',
      },
      { upsert: true, returnDocument: 'after' }
    );

    console.log('✅ Admin user created:', adminUser?.email, 'ID:', adminUser?._id);

    // Create dummy customers
    const customers = [
      {
        name: 'Rajesh Kumar',
        email: 'rajesh@example.com',
        phone: '+91 9876543210',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'active',
      },
      {
        name: 'Priya Singh',
        email: 'priya@example.com',
        phone: '+91 9876543211',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'active',
      },
      {
        name: 'Amit Patel',
        email: 'amit@example.com',
        phone: '+91 9876543212',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'active',
      },
      {
        name: 'Neha Sharma',
        email: 'neha@example.com',
        phone: '+91 9876543213',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'inactive',
      },
      {
        name: 'Vikram Desai',
        email: 'vikram@example.com',
        phone: '+91 9876543214',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'active',
      },
      {
        name: 'Anjali Gupta',
        email: 'anjali@example.com',
        phone: '+91 9876543215',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'active',
      },
      {
        name: 'Suresh Iyer',
        email: 'suresh@example.com',
        phone: '+91 9876543216',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'active',
      },
      {
        name: 'Meera Nair',
        email: 'meera@example.com',
        phone: '+91 9876543217',
        password: '$2y$10$IgXUSTvOWgt69BzBMuF6deBSFkZ/1sAMyVK93fExOpW5od989m01u',
        role: userType?._id,
        status: 'inactive',
      },
    ];

    console.log('👥 Creating', customers.length, 'dummy customers...');
    let insertedCount = 0;
    for (const customerData of customers) {
      const result = await User.findOneAndUpdate(
        { email: customerData.email },
        customerData,
        { upsert: true, returnDocument: 'after' }
      );
      if (result) {
        insertedCount++;
        console.log(`  ✅ ${result.name} (${result.email}) - ID: ${result._id}`);
      }
    }

    // Seed Indian states
    console.log('📍 Seeding Indian states...');
    const indianStates = [
      { name: 'Andhra Pradesh' },
      { name: 'Arunachal Pradesh' },
      { name: 'Assam' },
      { name: 'Bihar' },
      { name: 'Chhattisgarh' },
      { name: 'Goa' },
      { name: 'Gujarat' },
      { name: 'Haryana' },
      { name: 'Himachal Pradesh' },
      { name: 'Jharkhand' },
      { name: 'Karnataka' },
      { name: 'Kerala' },
      { name: 'Madhya Pradesh' },
      { name: 'Maharashtra' },
      { name: 'Manipur' },
      { name: 'Meghalaya' },
      { name: 'Mizoram' },
      { name: 'Nagaland' },
      { name: 'Odisha' },
      { name: 'Punjab' },
      { name: 'Rajasthan' },
      { name: 'Sikkim' },
      { name: 'Tamil Nadu' },
      { name: 'Telangana' },
      { name: 'Tripura' },
      { name: 'Uttar Pradesh' },
      { name: 'Uttarakhand' },
      { name: 'West Bengal' }
    ];

    let statesInserted = 0;
    for (const s of indianStates) {
      const res = await State.findOneAndUpdate({ name: s.name }, s, { upsert: true, returnDocument: 'after' });
      if (res) statesInserted++;
    }
    console.log(`✅ Seeded ${statesInserted} Indian states`);

    // Seed sample inquiries for testing
    console.log('✉️ Seeding sample inquiries...');
    const sampleInquiries = [
      {
        firstName: 'Aarav',
        lastName: 'Sharma',
        email: 'aarav.sharma@example.com',
        mobile: '+91 9000000001',
        orderNumber: 'ORD-1001',
        feedback: 'Inquiry about product sizing and availability.'
      },
      {
        firstName: 'Isha',
        lastName: 'Verma',
        email: 'isha.verma@example.com',
        mobile: '+91 9000000002',
        orderNumber: 'ORD-1002',
        feedback: 'Requesting return instructions for damaged item.'
      },
      {
        firstName: 'Kabir',
        lastName: 'Patel',
        email: 'kabir.patel@example.com',
        mobile: '+91 9000000003',
        orderNumber: '',
        feedback: 'General question about bulk orders.'
      },
      {
        firstName: 'Maya',
        lastName: 'Nair',
        email: 'maya.nair@example.com',
        mobile: '+91 9000000004',
        orderNumber: 'ORD-1004',
        feedback: 'Where can I find warranty information?'
      },
      {
        firstName: 'Rohit',
        lastName: 'Kumar',
        email: 'rohit.kumar@example.com',
        mobile: '+91 9000000005',
        orderNumber: 'ORD-1005',
        feedback: 'Need help tracking my shipment.'
      }
    ];

    let inquiriesInserted = 0;
    for (const iq of sampleInquiries) {
      const q = await Inquiry.findOneAndUpdate(
        { email: iq.email, mobile: iq.mobile },
        iq,
        { upsert: true, returnDocument: 'after' }
      );
      if (q) inquiriesInserted++;
    }
    console.log(`✅ Seeded ${inquiriesInserted} sample inquiries`);

    console.log('\n🎉 Seeding completed successfully!');
    console.log(`   - User Types: 2 (Admin + Customer)`);
    console.log(`   - Admin Users: 1`);
    console.log(`   - Customer Users: ${insertedCount}`);
  } catch (error) {
    console.error('❌ Seeding error:', error);
    process.exit(1);
  } finally {
    await mongoose.connection.close();
    console.log('📴 Database connection closed');
  }
}

seed();