//! XDG-based path resolution. Kept separate from the rest so tests can
//! substitute a `Paths` value pointing at a tempdir.

use std::path::{ Path, PathBuf };

use anyhow::{ Context, Result, anyhow };
use directories::BaseDirs;

#[ derive( Debug, Clone ) ]
pub struct Paths
{
	/// `$XDG_DATA_HOME/liberux/calllog` — holds `calllog.db`.
	pub data_dir: PathBuf,
	pub calllog_db: PathBuf,
}

impl Paths
{
	pub fn resolve() -> Result<Self>
	{
		let base = BaseDirs::new().ok_or_else( || anyhow!( "no XDG base dirs available" ) )?;
		Ok( Self::from_base( &base ) )
	}

	pub fn from_base( base: &BaseDirs ) -> Self
	{
		let data_dir = base.data_dir().join( "liberux/calllog" );
		Self
		{
			calllog_db: data_dir.join( "calllog.db" ),
			data_dir,
		}
	}

	/// Build a `Paths` rooted at `root`. Used by tests to keep state out of
	/// the user's real XDG dirs.
	pub fn under_root( root: &Path ) -> Self
	{
		let data_dir = root.join( "data/liberux/calllog" );
		Self
		{
			calllog_db: data_dir.join( "calllog.db" ),
			data_dir,
		}
	}

	pub fn ensure_dirs( &self ) -> Result<()>
	{
		std::fs::create_dir_all( &self.data_dir )
			.with_context( || format!( "creating {}", self.data_dir.display() ) )?;
		Ok( () )
	}
}
