const mongoose = require('mongoose');
const User = require('../models/User');
const crypto = require('crypto');
require('dotenv').config();

// Test users data
const testUsers = [
    {
        name: 'John Doe',
        mobile: '+1234567890',
        dob: new Date('1990-05-15'),
        password: 'password123',
        isVerified: true,
        otp: undefined
    },
    {
        name: 'Jane Smith',
        mobile: '+1234567891',
        dob: new Date('1985-12-20'),
        password: 'password456',
        isVerified: true,
        otp: undefined
    },
    {
        name: 'Mike Johnson',
        mobile: '+1234567892',
        dob: new Date('1992-08-10'),
        password: 'password789',
        isVerified: false,
        otp: {
            code: '123456',
            expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10 minutes from now
        }
    },
    {
        name: 'Sarah Wilson',
        mobile: '+1234567893',
        dob: new Date('1988-03-25'),
        password: 'password101',
        isVerified: false,
        otp: {
            code: '654321',
            expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10 minutes from now
        }
    },
    {
        name: 'David Brown',
        mobile: '+1234567894',
        dob: new Date('1995-11-30'),
        password: 'password202',
        isVerified: true,
        otp: undefined
    },
    {
        name: 'Emily Davis',
        mobile: '+1234567895',
        dob: new Date('1993-07-14'),
        password: 'password303',
        isVerified: false,
        otp: {
            code: '111111',
            expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10 minutes from now
        }
    },
    {
        name: 'Admin User',
        mobile: '+1111111111',
        dob: new Date('1980-01-01'),
        password: 'admin123',
        isVerified: true,
        otp: undefined
    }
];

// Connect to MongoDB
const connectDB = async () => {
    try {
        const MONGODB_URL = process.env.MONGODB_URL || 'mongodb://135.181.103.182:1200/recon_db';
        
        const options = {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            serverSelectionTimeoutMS: 5000,
            socketTimeoutMS: 45000,
            family: 4
        };

        await mongoose.connect(MONGODB_URL, options);
        console.log('✅ Connected to MongoDB');
    } catch (error) {
        console.error('❌ MongoDB connection error:', error.message);
        process.exit(1);
    }
};

// Seed users function
const seedUsers = async () => {
    try {
        console.log('🚀 Starting user seeding...');
        
        // Clear existing users
        await User.deleteMany({});
        console.log('🗑️  Cleared existing users');
        
        // Insert test users (passwords will be hashed by User model pre-save middleware)
        const createdUsers = await User.insertMany(testUsers);
        console.log(`✅ Created ${createdUsers.length} test users`);
        
        // Display created users
        console.log('\n📋 Test Users Created:');
        console.log('=' .repeat(80));
        
        createdUsers.forEach((user, index) => {
            console.log(`${index + 1}. Name: ${user.name}`);
            console.log(`   Mobile: ${user.mobile}`);
            console.log(`   Password: ${testUsers[index].password} (plain text for testing)`);
            console.log(`   DOB: ${user.dob.toISOString().split('T')[0]}`);
            console.log(`   Verified: ${user.isVerified ? '✅ Yes' : '❌ No'}`);
            if (!user.isVerified && user.otp) {
                console.log(`   OTP: ${user.otp.code} (expires: ${user.otp.expiresAt.toLocaleString()})`);
            }
            console.log(`   User ID: ${user._id}`);
            console.log('-'.repeat(80));
        });
        
        console.log('\n🔑 Login Credentials for Testing:');
        console.log('=' .repeat(80));
        
        const verifiedUsers = createdUsers.filter(user => user.isVerified);
        verifiedUsers.forEach((user, index) => {
            console.log(`${index + 1}. Mobile: ${user.mobile} | Password: ${testUsers.find(tu => tu.mobile === user.mobile).password}`);
        });
        
        console.log('\n📱 OTP Verification for Unverified Users:');
        console.log('=' .repeat(80));
        
        const unverifiedUsers = createdUsers.filter(user => !user.isVerified);
        unverifiedUsers.forEach((user, index) => {
            console.log(`${index + 1}. Mobile: ${user.mobile} | OTP: ${user.otp.code}`);
        });
        
        console.log('\n🎯 API Endpoints for Testing:');
        console.log('=' .repeat(80));
        console.log('POST /api/users/register - Register new user');
        console.log('POST /api/users/verify-otp - Verify OTP');
        console.log('POST /api/users/resend-otp - Resend OTP');
        console.log('POST /api/auth/login - Login user');
        console.log('GET /api/auth/profile/:userId - Get user profile');
        console.log('GET /api/users/all - Get all users (for testing)');
        
        console.log('\n✅ User seeding completed successfully!');
        
    } catch (error) {
        console.error('❌ Seeding error:', error);
    } finally {
        await mongoose.connection.close();
        console.log('🔌 Database connection closed');
        process.exit(0);
    }
};

// Run the seeding
const runSeed = async () => {
    await connectDB();
    await seedUsers();
};

// Handle script execution
if (require.main === module) {
    runSeed();
}

module.exports = { seedUsers, testUsers };
