use crate::state::ServiceRegistry;
use common_contracts::registry::{ServiceRegistration, ServiceRole, ProviderMetadata, ConfigFieldSchema, FieldType, ConfigKey};

#[test]
fn test_registry_crud() {
    let registry = ServiceRegistry::new();
    let service_id = "test-service-1";
    
    // 1. Register
    let registration = ServiceRegistration {
        service_id: service_id.to_string(),
        service_name: "test_provider".to_string(),
        role: ServiceRole::DataProvider,
        base_url: "http://localhost:8000".to_string(),
        health_check_url: "http://localhost:8000/health".to_string(),
        metadata: Some(ProviderMetadata {
            id: "test_provider".to_string(),
            name_en: "Test Provider".to_string(),
            name_cn: "测试服务".to_string(),
            description: "Test".to_string(),
            icon_url: None,
            config_schema: vec![
                ConfigFieldSchema {
                    key: ConfigKey::ApiKey,
                    label: "API Key".to_string(),
                    field_type: FieldType::Password,
                    required: true,
                    placeholder: None,
                    default_value: None,
                    description: None,
                    options: None,
                }
            ],
            supports_test_connection: true,
        }),
    };
    
    registry.register(registration.clone());
    
    // Verify registration
    assert_eq!(registry.get_provider_count(), 1);
    assert!(registry.get_service_url("test_provider").is_some());
    
    // 2. Heartbeat
    assert!(registry.update_heartbeat(service_id));
    assert!(!registry.update_heartbeat("unknown-service"));
    
    // 3. Discovery logic
    let services = registry.get_all_services();
    assert_eq!(services.len(), 1);
    assert_eq!(services[0].0, service_id);
    
    let entries = registry.get_entries();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].registration.metadata.as_ref().unwrap().id, "test_provider");

    // 4. Deregister
    assert!(registry.deregister(service_id));
    assert_eq!(registry.get_provider_count(), 0);
    assert!(registry.get_service_url("test_provider").is_none());
    
    // Deregister unknown should return false
    assert!(!registry.deregister(service_id));
}
