sekrit 1.0.0

Encrypt any file, decrypt anywhere. File encryption that doesn't suck.
Documentation
use crate::types::EncryptedFile;
use anyhow::{Result, anyhow};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::Path;

pub struct FileOps;

impl FileOps {
    pub fn read_file(path: &Path) -> Result<Vec<u8>> {
        let mut file = File::open(path)?;
        let mut buffer = Vec::new();
        file.read_to_end(&mut buffer)?;
        Ok(buffer)
    }

    pub fn write_encrypted_file(path: &Path, encrypted_file: &EncryptedFile) -> Result<()> {
        // Serialize metadata + write to file
        let file_data = encrypted_file.to_json_bytes()?;
        let mut file = OpenOptions::new()
            .create(true)
            .truncate(true)
            .write(true)
            .open(path)?;
        file.write_all(&file_data)?;
        Ok(())
    }

    pub fn read_encrypted_file(path: &Path) -> Result<EncryptedFile> {
        // Read file + deserialize metadata
        let file_data = Self::read_file(path)?;
        let encrypted_file = EncryptedFile::from_json_bytes(&file_data)?;
        Ok(encrypted_file)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_encrypted_file() -> EncryptedFile {
        EncryptedFile::new(
            "dGVzdF9zYWx0".to_string(),
            "dGVzdF9ub25jZQ==".to_string(),
            "dGVzdF9jaXBoZXJ0ZXh0".to_string(),
        )
    }

    #[test]
    fn test_read_file_success() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("test.txt");

        let test_data = b"Hello, World! This is test data.";
        fs::write(&file_path, test_data).expect("Failed to write test file");

        let result = FileOps::read_file(&file_path).expect("Failed to read file");
        assert_eq!(result, test_data);
    }

    #[test]
    fn test_read_file_nonexistent() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("nonexistent.txt");

        let result = FileOps::read_file(&file_path);
        assert!(result.is_err(), "Reading nonexistent file should fail");
    }

    #[test]
    fn test_read_empty_file() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("empty.txt");

        fs::write(&file_path, b"").expect("Failed to create empty file");

        let result = FileOps::read_file(&file_path).expect("Failed to read empty file");
        assert_eq!(result, Vec::<u8>::new());
    }

    #[test]
    fn test_read_large_file() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("large.txt");

        let large_data = vec![42u8; 1024 * 1024]; // 1MB
        fs::write(&file_path, &large_data).expect("Failed to write large file");

        let result = FileOps::read_file(&file_path).expect("Failed to read large file");
        assert_eq!(result, large_data);
    }

    #[test]
    fn test_write_encrypted_file_success() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("encrypted.json");

        let encrypted_file = create_test_encrypted_file();

        FileOps::write_encrypted_file(&file_path, &encrypted_file)
            .expect("Failed to write encrypted file");

        // Verify file was created
        assert!(file_path.exists(), "File should exist after writing");

        // Verify file contains valid JSON
        let file_contents = fs::read_to_string(&file_path).expect("Failed to read written file");
        assert!(file_contents.contains("\"version\""));
        assert!(file_contents.contains("\"salt\""));
        assert!(file_contents.contains("\"nonce\""));
        assert!(file_contents.contains("\"ciphertext\""));
        assert!(file_contents.contains("\"created_at\""));
    }

    #[test]
    fn test_write_encrypted_file_overwrites() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("overwrite.json");

        // Write initial file
        fs::write(&file_path, "initial content").expect("Failed to write initial file");

        let encrypted_file = create_test_encrypted_file();

        FileOps::write_encrypted_file(&file_path, &encrypted_file)
            .expect("Failed to overwrite file");

        // Verify old content was overwritten
        let file_contents =
            fs::read_to_string(&file_path).expect("Failed to read overwritten file");
        assert!(!file_contents.contains("initial content"));
        assert!(file_contents.contains("\"version\""));
    }

    #[test]
    fn test_read_encrypted_file_success() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("test_encrypted.json");

        let original_encrypted_file = create_test_encrypted_file();

        // Write the file first
        FileOps::write_encrypted_file(&file_path, &original_encrypted_file)
            .expect("Failed to write encrypted file");

        // Read it back
        let read_encrypted_file =
            FileOps::read_encrypted_file(&file_path).expect("Failed to read encrypted file");

        // Verify all fields match
        assert_eq!(read_encrypted_file.version, original_encrypted_file.version);
        assert_eq!(read_encrypted_file.salt, original_encrypted_file.salt);
        assert_eq!(read_encrypted_file.nonce, original_encrypted_file.nonce);
        assert_eq!(
            read_encrypted_file.ciphertext,
            original_encrypted_file.ciphertext
        );
        assert_eq!(
            read_encrypted_file.created_at,
            original_encrypted_file.created_at
        );
    }

    #[test]
    fn test_read_encrypted_file_nonexistent() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("nonexistent.json");

        let result = FileOps::read_encrypted_file(&file_path);
        assert!(
            result.is_err(),
            "Reading nonexistent encrypted file should fail"
        );
    }

    #[test]
    fn test_read_encrypted_file_invalid_json() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("invalid.json");

        // Write invalid JSON
        fs::write(&file_path, "{ invalid json }").expect("Failed to write invalid JSON");

        let result = FileOps::read_encrypted_file(&file_path);
        assert!(result.is_err(), "Reading invalid JSON should fail");
    }

    #[test]
    fn test_read_encrypted_file_incomplete_json() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("incomplete.json");

        // Write incomplete JSON (missing required fields)
        fs::write(&file_path, r#"{"version": 1}"#).expect("Failed to write incomplete JSON");

        let result = FileOps::read_encrypted_file(&file_path);
        assert!(result.is_err(), "Reading incomplete JSON should fail");
    }

    #[test]
    fn test_write_read_roundtrip() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("roundtrip.json");

        let original = create_test_encrypted_file();

        // Write then read
        FileOps::write_encrypted_file(&file_path, &original).expect("Failed to write file");

        let read_back = FileOps::read_encrypted_file(&file_path).expect("Failed to read file");

        // Verify perfect roundtrip
        assert_eq!(original.version, read_back.version);
        assert_eq!(original.salt, read_back.salt);
        assert_eq!(original.nonce, read_back.nonce);
        assert_eq!(original.ciphertext, read_back.ciphertext);
        assert_eq!(original.created_at, read_back.created_at);
    }

    #[test]
    fn test_write_multiple_files() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        let files = vec![
            (
                "file1.json",
                EncryptedFile::new(
                    "salt1".to_string(),
                    "nonce1".to_string(),
                    "cipher1".to_string(),
                ),
            ),
            (
                "file2.json",
                EncryptedFile::new(
                    "salt2".to_string(),
                    "nonce2".to_string(),
                    "cipher2".to_string(),
                ),
            ),
            (
                "file3.json",
                EncryptedFile::new(
                    "salt3".to_string(),
                    "nonce3".to_string(),
                    "cipher3".to_string(),
                ),
            ),
        ];

        // Write all files
        for (filename, encrypted_file) in &files {
            let file_path = temp_dir.path().join(filename);
            FileOps::write_encrypted_file(&file_path, encrypted_file)
                .expect("Failed to write file");
        }

        // Read all files back and verify
        for (filename, original) in &files {
            let file_path = temp_dir.path().join(filename);
            let read_back = FileOps::read_encrypted_file(&file_path).expect("Failed to read file");

            assert_eq!(original.salt, read_back.salt);
            assert_eq!(original.nonce, read_back.nonce);
            assert_eq!(original.ciphertext, read_back.ciphertext);
        }
    }

    #[test]
    fn test_unicode_filename() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("测试文件_🔐.json");

        let encrypted_file = create_test_encrypted_file();

        FileOps::write_encrypted_file(&file_path, &encrypted_file)
            .expect("Failed to write file with unicode name");

        let read_back = FileOps::read_encrypted_file(&file_path)
            .expect("Failed to read file with unicode name");

        assert_eq!(encrypted_file.salt, read_back.salt);
    }

    #[test]
    fn test_nested_directory_creation() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let nested_path = temp_dir
            .path()
            .join("nested")
            .join("deep")
            .join("file.json");

        // Create parent directories
        fs::create_dir_all(nested_path.parent().unwrap())
            .expect("Failed to create nested directories");

        let encrypted_file = create_test_encrypted_file();

        FileOps::write_encrypted_file(&nested_path, &encrypted_file)
            .expect("Failed to write to nested path");

        let read_back =
            FileOps::read_encrypted_file(&nested_path).expect("Failed to read from nested path");

        assert_eq!(encrypted_file.version, read_back.version);
    }
}