import mongoose, { Types } from 'mongoose';
import 'dotenv/config';
import QRCodeModel from '../models/QrCode';
import UserModel from '../models/User';

class PetQRCodeSeeder {
    private static async connectToDatabase(): Promise<void> {
        try {
            if (mongoose.connection.readyState === 0) {
                await mongoose.connect(process.env.DATABASE_URL!);
                console.log('✅ Connected to MongoDB');
            }
        } catch (error) {
            console.error('❌ Database connection failed:', error);
            throw error;
        }
    }

    private static generatePetQRCodeData(userId: Types.ObjectId, imageId: Types.ObjectId, index: number): any {
        // Generate realistic pet data
        const petNames = [
            'Buddy', 'Max', 'Charlie', 'Cooper', 'Jack', 'Rocky', 'Bear', 'Duke', 'Toby', 'Tucker',
            'Jake', 'Prince', 'Zeus', 'Apollo', 'Bailey', 'Buster', 'Cody', 'Gizmo', 'Harley', 'Jax',
            'Lucky', 'Milo', 'Murphy', 'Oliver', 'Oscar', 'Rex', 'Riley', 'Rocky', 'Sam', 'Scout',
            'Shadow', 'Simba', 'Thor', 'Winston', 'Ziggy', 'Luna', 'Bella', 'Lucy', 'Daisy', 'Lily',
            'Lola', 'Sadie', 'Molly', 'Bailey', 'Maggie', 'Sophie', 'Chloe', 'Stella', 'Zoey', 'Roxy'
        ];

        const breeds = [
            'Labrador Retriever', 'German Shepherd', 'Golden Retriever', 'French Bulldog', 'Bulldog',
            'Poodle', 'Beagle', 'Rottweiler', 'German Shorthaired Pointer', 'Dachshund',
            'Corgi', 'Australian Shepherd', 'Yorkshire Terrier', 'Boxer', 'Siberian Husky',
            'Great Dane', 'Doberman Pinscher', 'Shih Tzu', 'Boston Terrier', 'Miniature Schnauzer',
            'Brittany', 'Cavalier King Charles Spaniel', 'Pomeranian', 'Bernese Mountain Dog',
            'Shetland Sheepdog', 'Havanese', 'Border Collie', 'English Springer Spaniel',
            'Maine Coon', 'Persian', 'Siamese', 'Ragdoll', 'Bengal', 'Scottish Fold',
            'British Shorthair', 'Sphynx', 'Abyssinian', 'Russian Blue', 'Birman'
        ];

        const vaccinationStatuses = ['up_to_date', 'not_current', 'unknown'];

        // Select random values
        const petName = petNames[Math.floor(Math.random() * petNames.length)];
        const breed = breeds[Math.floor(Math.random() * breeds.length)];
        const age = Math.floor(Math.random() * 15) + 1; // 1-15 years
        const weight = parseFloat((Math.random() * 48 + 2).toFixed(1)); // 2-50 kg
        const vaccinationStatus = vaccinationStatuses[Math.floor(Math.random() * vaccinationStatuses.length)];

        // Generate owner name
        const firstNames = ['John', 'Jane', 'Michael', 'Sarah', 'David', 'Emily', 'Christopher', 'Jessica', 'Matthew', 'Ashley'];
        const lastNames = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez'];
        const ownerName = firstNames[Math.floor(Math.random() * firstNames.length)] + ' ' + lastNames[Math.floor(Math.random() * lastNames.length)];

        // Generate contact info
        const contactEmail = `${ownerName.replace(/\s+/g, '.').toLowerCase()}@example.com`;
        const contactPhone = `+1-${Math.floor(Math.random() * 900 + 100)}-${Math.floor(Math.random() * 900 + 100)}-${Math.floor(Math.random() * 9000 + 1000)}`;

        // Create type-specific details for PET QR codes
        const typeDetails = {
            pet_name: petName,
            breed: breed,
            age: age,
            weight: weight,
            owner_name: ownerName,
            contact_email: contactEmail,
            contact_phone: contactPhone,
            vaccination_status: vaccinationStatus,
            special_needs: Math.random() > 0.7 ? 'Requires medication twice daily' : 'None'
        };

        // Return the QR code data object
        return {
            title: `Pet Profile - ${petName}`,
            type: 'PET',
            item_name: petName,
            item_description: `A lovely ${breed} who is ${age} years old and weighs ${weight} kg.`,
            name: petName,
            description: {
                text: `${petName} is a friendly ${breed} who loves to play and go for walks. ${petName} is ${age} years old and weighs ${weight} kg.`,
                contact_info: {
                    phone: contactPhone,
                    email: contactEmail
                }
            },
            notes: `Additional information about ${petName}. Vaccination status: ${vaccinationStatus}.`,
            created_by: userId,
            access_type: 'PUBLIC',
            privacy_controls: {
                access_level: 'PUBLIC',
                access_password: null,
                is_disabled: false,
                allow_anonymous_messaging: true,
                emergency_notify: {
                    enabled: true,
                    contact_email: contactEmail,
                    contact_phone: contactPhone
                }
            },
            color: '#000000',
            background_color: '#FFFFFF',
            size: 256,
            status: 'ACTIVE',
            type_details: typeDetails,
            scan_count: Math.floor(Math.random() * 50), // Random scan count 0-49
            anonymous_scan_count: Math.floor(Math.random() * 20), // Random anonymous scan count 0-19
            images: [imageId], // Use the provided image ID
            location_enabled: Math.random() > 0.5 // 50% chance of having location enabled
        };
    }

    public static async seedPetQRCodes(count: number = 25): Promise<void> {
        try {
            await this.connectToDatabase();
            console.log(`🌱 Starting PET QR code seeding process with ${count} QR codes...`);

            // Use the specific user ID and image ID provided
            const userId = new Types.ObjectId('692ec6ce7a4a60c20fb22f34');
            const imageId = new Types.ObjectId('694936bcf626c491fcbf8072');

            console.log(`📝 Creating ${count} PET QR codes for user ${userId} with image ${imageId}...`);

            let createdCount = 0;

            for (let i = 0; i < count; i++) {
                const qrCodeData = this.generatePetQRCodeData(userId, imageId, i);

                const qrCode = new QRCodeModel(qrCodeData);
                await qrCode.save();

                createdCount++;
                console.log(`✅ Created PET QR code: ${qrCodeData.title} for user ${userId}`);
            }

            console.log(`\n🎉 Successfully created ${createdCount} PET QR codes for user ${userId}`);
        } catch (error) {
            console.error('❌ Error during seeding:', error);
            throw error;
        } finally {
            await mongoose.connection.close();
            console.log('🔌 Database connection closed');
        }
    }

    public static async resetPetQRCodes(): Promise<void> {
        try {
            await this.connectToDatabase();

            // Delete all PET QR codes created by the specific user ID
            const userId = new Types.ObjectId('692ec6ce7a4a60c20fb22f34');
            const deletedResult = await QRCodeModel.deleteMany({
                created_by: userId,
                type: 'PET'
            });
            console.log(`🗑️  Removed ${deletedResult.deletedCount} PET QR code(s) from user ${userId}`);
        } catch (error) {
            console.error('❌ Error during reset:', error);
            throw error;
        } finally {
            await mongoose.connection.close();
            console.log('🔌 Database connection closed');
        }
    }
}

// CLI execution support
if (require.main === module) {
    const command = process.argv[2];
    const countParam = parseInt(process.argv[3]) || 25;

    switch (command) {
        case 'seed':
            PetQRCodeSeeder.seedPetQRCodes(countParam)
                .then(() => process.exit(0))
                .catch(() => process.exit(1));
            break;

        case 'reset':
            PetQRCodeSeeder.resetPetQRCodes()
                .then(() => process.exit(0))
                .catch(() => process.exit(1));
            break;

        default:
            console.log('Usage:');
            console.log('  npm run seed:pet-qrcode seed [count]  - Seed PET QR codes (default: 25)');
            console.log('  npm run seed:pet-qrcode reset         - Remove all PET QR codes for the user');
            process.exit(1);
    }
}

export default PetQRCodeSeeder;