use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid;

/// Metadata for a stored backup.
#[derive(Debug, Clone, Serialize)]
pub struct BackupInfo {
    pub id: Uuid,
    pub license_id: Uuid,
    pub wipe_history_id: Option<Uuid>,
    pub storage_path: String,
    pub size_bytes: i64,
    pub created_at: DateTime<Utc>,
}

/// Pre-wipe backup and rollback management.
///
/// Creates snapshots of server state (map, save data, plugin data,
/// config files) before a wipe executes. Backups are used by the
/// wipe engine's rollback mechanism if post-wipe verification fails.
pub struct BackupManager {
    // TODO: Add fields:
    // - db: sqlx::PgPool
    // - storage_base_path: String
}

impl BackupManager {
    /// Create a pre-wipe backup of the server's current state.
    ///
    /// Captures: map/save files, plugin data directories, server.cfg,
    /// and any other files configured for backup in the wipe profile.
    /// Returns a backup reference ID stored in wipe_history.
    pub async fn create_backup(
        &self,
        _license_id: Uuid,
        _wipe_history_id: Uuid,
    ) -> Result<String> {
        // TODO: Resolve PanelAdapter for the server
        // TODO: Download save files (map, sav, player data) via adapter
        // TODO: Download plugin data directories via adapter
        // TODO: Download server.cfg via adapter
        // TODO: Bundle into archive (tar.gz)
        // TODO: Write archive to backup storage
        // TODO: Insert backup record in DB
        // TODO: Return backup reference string
        todo!()
    }

    /// Restore a previously created backup to the server.
    ///
    /// Used during rollback when post-wipe verification fails.
    pub async fn restore_backup(&self, _backup_reference: &str) -> Result<()> {
        // TODO: Load backup record from DB by reference
        // TODO: Read backup archive from storage
        // TODO: Extract archive contents
        // TODO: Upload files back to server via PanelAdapter
        // TODO: Log restoration details
        todo!()
    }

    /// List all backups for a license, ordered by creation date (newest first).
    pub async fn list_backups(&self, _license_id: Uuid) -> Result<Vec<BackupInfo>> {
        // TODO: Query backup records from DB for this license
        // TODO: Return sorted list
        todo!()
    }

    /// Clean up old backups beyond the configured retention period/count.
    pub async fn cleanup_old_backups(&self, _license_id: Uuid) -> Result<u32> {
        // TODO: Load retention config (max count or max age)
        // TODO: Query backups older than retention threshold
        // TODO: Delete backup files from storage
        // TODO: Delete backup records from DB
        // TODO: Return count of deleted backups
        todo!()
    }
}
