use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::AppResult;

pub(crate) struct TempFileGuard {
    path: PathBuf,
}

impl TempFileGuard {
    pub(crate) fn new(path: PathBuf) -> Self {
        Self { path }
    }

    pub(crate) fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TempFileGuard {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

pub(crate) fn write_temp_text_file(contents: &str) -> AppResult<TempFileGuard> {
    let path = temp_path("tgn-message", "txt")?;
    fs::write(&path, contents)?;
    Ok(TempFileGuard::new(path))
}

pub(crate) fn temp_path(prefix: &str, extension: &str) -> AppResult<PathBuf> {
    let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
    let pid = std::process::id();
    Ok(std::env::temp_dir().join(format!("{prefix}-{pid}-{now}.{extension}")))
}
