use std::{path::PathBuf, process::Command};

use crate::{
    config_store,
    models::{BrowserConfigListResponse, CreateCustomBrowserConfigInput, ScanResponse},
    scanner,
};
use tauri::AppHandle;

#[tauri::command]
pub fn scan_browsers(app: AppHandle) -> Result<ScanResponse, String> {
    scanner::scan_browsers(&app)
}

#[tauri::command]
pub fn list_browser_configs(app: AppHandle) -> Result<BrowserConfigListResponse, String> {
    config_store::load_browser_config_list(&app)
}

#[tauri::command]
pub fn create_custom_browser_config(
    app: AppHandle,
    input: CreateCustomBrowserConfigInput,
) -> Result<BrowserConfigListResponse, String> {
    config_store::create_custom_browser_config(&app, input)
}

#[tauri::command]
pub fn delete_custom_browser_config(
    app: AppHandle,
    config_id: String,
) -> Result<BrowserConfigListResponse, String> {
    config_store::delete_custom_browser_config(&app, &config_id)
}

#[tauri::command]
pub fn open_browser_profile(
    app: AppHandle,
    browser_id: String,
    profile_id: String,
) -> Result<(), String> {
    let config = config_store::find_browser_config(&app, &browser_id)?;
    let executable_path = PathBuf::from(&config.executable_path);
    let user_data_dir = PathBuf::from(&config.user_data_path);
    let profile_directory = user_data_dir.join(&profile_id);

    if !user_data_dir.is_dir() {
        return Err(format!(
            "User data directory does not exist: {}",
            user_data_dir.display()
        ));
    }

    if !profile_directory.is_dir() {
        return Err(format!(
            "Profile directory does not exist: {}",
            profile_directory.display()
        ));
    }

    spawn_browser_process(executable_path, user_data_dir, profile_id)
}

fn spawn_browser_process(
    executable_path: PathBuf,
    user_data_dir: PathBuf,
    profile_id: String,
) -> Result<(), String> {
    Command::new(&executable_path)
        .arg(format!("--user-data-dir={}", user_data_dir.display()))
        .arg(format!("--profile-directory={profile_id}"))
        .arg("https://www.google.com")
        .spawn()
        .map(|_| ())
        .map_err(|error| {
            format!(
                "Failed to open browser profile with executable {}: {error}",
                executable_path.display()
            )
        })
}
