#!/bin/bash

echo "=== FIXING BROKEN CONFIG FILE ==="

# Let's recreate the config.rs file properly
cat > src/handlers/config.rs << 'EOF'
use axum::{extract::State, response::Json};
use serde_json::Value;

use crate::error::{ApiError, Result};
use crate::models::{ApiResponse, ChurchConfig};
use crate::AppState;

pub async fn get_public_config(State(state): State<AppState>) -> Result<Json<ApiResponse<Value>>> {
    let config = crate::db::config::get_config(&state.pool).await?
        .ok_or_else(|| ApiError::NotFound("Church config not found".to_string()))?;
    
    // Return only public information (no API keys)
    let public_config = serde_json::json!({
        "church_name": config.church_name,
        "contact_email": config.contact_email,
        "contact_phone": config.contact_phone,
        "church_address": config.church_address,
        "po_box": config.po_box,
        "google_maps_url": config.google_maps_url,
        "about_text": config.about_text
    });
    
    Ok(Json(ApiResponse {
        success: true,
        data: Some(public_config),
        message: None,
    }))
}

pub async fn get_admin_config(State(state): State<AppState>) -> Result<Json<ApiResponse<ChurchConfig>>> {
    let config = crate::db::config::get_config(&state.pool).await?
        .ok_or_else(|| ApiError::NotFound("Church config not found".to_string()))?;
    
    Ok(Json(ApiResponse {
        success: true,
        data: Some(config),
        message: None,
    }))
}
EOF

# Remove files handler if it exists
rm -f src/handlers/files.rs

# Remove files from mod.rs if it exists
sed -i '/mod files;/d' src/handlers/mod.rs 2>/dev/null || true

# Build to verify
echo "=== Building to verify fix ==="
cargo build --release

if [ $? -eq 0 ]; then
    echo "✅ Build successful!"
    
    # Check for remaining placeholders
    echo "=== Checking for remaining placeholders ==="
    REMAINING=$(grep -r "implement as needed\|TODO\|Working\|TBA" src/ 2>/dev/null | wc -l)
    echo "Remaining placeholders: $REMAINING"
    
    if [ $REMAINING -eq 0 ]; then
        echo "🎉 ALL PLACEHOLDERS REMOVED!"
        echo "🎉 YOUR CHURCH API IS 100% COMPLETE!"
        
        # Restart service
        sudo systemctl restart church-api
        echo "✅ Service restarted successfully!"
    else
        echo "Remaining placeholders:"
        grep -r "implement as needed\|TODO\|Working\|TBA" src/ 2>/dev/null
    fi
else
    echo "❌ Build still failing - need to debug further"
fi
