use mongodb::{
    Client,
    Collection,
    bson::doc,
    IndexModel,
};

use anyhow::Result;

pub struct DatabaseInitializer {
    client: Client,
    db_name: String,
}

impl DatabaseInitializer {
    pub fn new(client: Client, db_name: String) -> Self {
        Self { client, db_name }
    }

    pub async fn initialize(&self) -> Result<()> {
        let db = self.client.database(&self.db_name);

        println!("[MongoDB] Initializing database collections and indexes...");

        // Create users collection and index
        {
            let collection: Collection<mongodb::bson::Document> = db.collection("users");
            
            // Create email index using the builder pattern
            let index = IndexModel::builder()
                .keys(doc! { "email": 1 })
                .options(mongodb::options::IndexOptions::builder().unique(true).build())
                .build();
            
            match collection.create_index(index, None).await {
                Ok(_) => println!("✓ Created index on users.email"),
                Err(e) => println!("Warning: Failed to create index on users.email: {}", e),
            }
        }

        // Create families collection and indexes
        {
            let collection: Collection<mongodb::bson::Document> = db.collection("families");
            
            let index1 = IndexModel::builder()
                .keys(doc! { "userId": 1 })
                .build();
            
            let index2 = IndexModel::builder()
                .keys(doc! { "familyId": 1 })
                .build();
            
            match collection.create_index(index1, None).await {
                Ok(_) => println!("✓ Created index on families.userId"),
                Err(e) => println!("Warning: Failed to create index on families.userId: {}", e),
            }
            
            match collection.create_index(index2, None).await {
                Ok(_) => println!("✓ Created index on families.familyId"),
                Err(e) => println!("Warning: Failed to create index on families.familyId: {}", e),
            }
        }

        // Create profiles collection and index
        {
            let collection: Collection<mongodb::bson::Document> = db.collection("profiles");
            
            let index = IndexModel::builder()
                .keys(doc! { "familyId": 1 })
                .build();
            
            match collection.create_index(index, None).await {
                Ok(_) => println!("✓ Created index on profiles.familyId"),
                Err(e) => println!("Warning: Failed to create index on profiles.familyId: {}", e),
            }
        }

        // Create health_data collection
        {
            let _collection: Collection<mongodb::bson::Document> = db.collection("health_data");
            println!("✓ Created health_data collection");
        }

        // Create lab_results collection
        {
            let _collection: Collection<mongodb::bson::Document> = db.collection("lab_results");
            println!("✓ Created lab_results collection");
        }

        // Create medications collection
        {
            let _collection: Collection<mongodb::bson::Document> = db.collection("medications");
            println!("✓ Created medications collection");
        }

        // Create appointments collection
        {
            let _collection: Collection<mongodb::bson::Document> = db.collection("appointments");
            println!("✓ Created appointments collection");
        }

        // Create shares collection and index
        {
            let collection: Collection<mongodb::bson::Document> = db.collection("shares");
            
            let index = IndexModel::builder()
                .keys(doc! { "familyId": 1 })
                .build();
            
            match collection.create_index(index, None).await {
                Ok(_) => println!("✓ Created index on shares.familyId"),
                Err(e) => println!("Warning: Failed to create index on shares.familyId: {}", e),
            }
        }

        // Create refresh_tokens collection and index
        {
            let collection: Collection<mongodb::bson::Document> = db.collection("refresh_tokens");
            
            let index = IndexModel::builder()
                .keys(doc! { "token": 1 })
                .options(mongodb::options::IndexOptions::builder().unique(true).build())
                .build();
            
            match collection.create_index(index, None).await {
                Ok(_) => println!("✓ Created index on refresh_tokens.token"),
                Err(e) => println!("Warning: Failed to create index on refresh_tokens.token: {}", e),
            }
        }

        println!("[MongoDB] Database initialization complete");
        Ok(())
    }
}
