// src/tui/functions/common/logout.rs
use crate::config::storage::delete_auth_data;
use crate::state::pages::auth::AuthState;
use crate::state::app::state::AppState;
use crate::state::app::buffer::{AppView, BufferState};
use crate::ui::handlers::context::DialogPurpose;
use tracing::{error, info};

pub fn logout(
    auth_state: &mut AuthState,
    app_state: &mut AppState,
    buffer_state: &mut BufferState,
) -> String {
    // Clear auth state in memory
    auth_state.auth_token = None;
    auth_state.user_id = None;
    auth_state.role = None;
    auth_state.decoded_username = None;
    
    // Delete stored auth data
    if let Err(e) = delete_auth_data() {
        error!("Failed to delete stored auth data: {}", e);
        // Continue anyway - user is logged out in memory
    }
    
    // Navigate to intro screen
    buffer_state.history = vec![AppView::Intro];
    buffer_state.active_index = 0;
    
    // Reset UI state
    app_state.ui.focus_outside_canvas = false;
    app_state.focused_button_index = 0;
    
    // Hide any open dialogs
    app_state.hide_dialog();
    
    // Show logout confirmation dialog
    app_state.show_dialog(
        "Logged Out",
        "You have been successfully logged out.",
        vec!["OK".to_string()],
        DialogPurpose::LoginSuccess, // Reuse or create a new purpose
    );
    
    info!("User logged out successfully.");
    "Logged out successfully".to_string()
}
