pub mod client;

use crate::error::AppResult;
use client::MdmClient;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MdmCommandResult {
    pub command_uuid: String,
    pub response_body: String,
}

#[tauri::command]
pub async fn mdm_ping() -> AppResult<String> {
    MdmClient::new()?.ping().await
}

#[tauri::command]
pub async fn mdm_push(udid: String) -> AppResult<client::MdmPushStatus> {
    MdmClient::new()?.push(&udid).await
}

#[tauri::command]
pub async fn mdm_install_app(udid: String) -> AppResult<MdmCommandResult> {
    let command = serde_json::json!({
        "RequestType": "InstallApplication",
        "ManifestURL": "https://mdm.rebreak.org/install/manifest.plist",
        "ManagementFlags": 0,
    });
    let r = MdmClient::new()?.enqueue(&udid, command).await?;
    Ok(MdmCommandResult {
        command_uuid: r.command_uuid,
        response_body: r.response_body,
    })
}

#[tauri::command]
pub async fn mdm_set_supervised_mode(udid: String) -> AppResult<MdmCommandResult> {
    let command = serde_json::json!({
        "RequestType": "Settings",
        "Settings": [
            {
                "Item": "ApplicationConfiguration",
                "Identifier": "org.rebreak.app",
                "Configuration": {
                    "mdmSupervised": true,
                },
            },
        ],
    });
    let r = MdmClient::new()?.enqueue(&udid, command).await?;
    Ok(MdmCommandResult {
        command_uuid: r.command_uuid,
        response_body: r.response_body,
    })
}

#[tauri::command]
pub async fn mdm_take_management(udid: String) -> AppResult<MdmCommandResult> {
    let command = serde_json::json!({
        "RequestType": "InstallApplication",
        "Identifier": "org.rebreak.app",
        "ChangeManagementState": "Managed",
        "ManagementFlags": 0,
    });
    let r = MdmClient::new()?.enqueue(&udid, command).await?;
    Ok(MdmCommandResult {
        command_uuid: r.command_uuid,
        response_body: r.response_body,
    })
}

#[tauri::command]
pub async fn mdm_install_lock_profile(udid: String, profile_path: String) -> AppResult<MdmCommandResult> {
    let bytes = std::fs::read(&profile_path)?;
    let payload_b64 = {
        use base64::{engine::general_purpose::STANDARD, Engine};
        STANDARD.encode(&bytes)
    };
    let command = serde_json::json!({
        "RequestType": "InstallProfile",
        "Payload": payload_b64,
    });
    let r = MdmClient::new()?.enqueue(&udid, command).await?;
    Ok(MdmCommandResult {
        command_uuid: r.command_uuid,
        response_body: r.response_body,
    })
}
