/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use crate::{Config, backends::CacheStorage};
use anyhow::{Result, bail};
use rand::random;
use std::{
    fs::{File, create_dir_all, rename},
    io::{ErrorKind, Read, Write},
    path::PathBuf,
};

pub struct Filesystem(PathBuf);

impl Filesystem {
    pub fn new(config: &Config) -> Self {
        Self(config.path.clone())
    }
    fn temp_path(&self) -> PathBuf {
        self.0.join(format!("temp-{:016x}", random::<u128>()))
    }
}

impl CacheStorage for Filesystem {
    fn store(&self, key: String, value: &[u8]) -> Result<()> {
        let temp = self.temp_path();
        let out = self.0.join(&key);
        create_dir_all(out.parent().unwrap())?;
        File::create(&temp)?.write_all(value)?;
        rename(temp, out)?;
        Ok(())
    }
    fn read(&self, key: &str) -> Result<Option<Vec<u8>>> {
        if key.contains("..") || key.starts_with("/") {
            bail!("invalid key")
        }
        match File::open(self.0.join(key)) {
            Ok(mut f) => {
                let mut data = Vec::new();
                f.read_to_end(&mut data)?;
                Ok(Some(data))
            }
            Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e.into()),
        }
    }
}
