use chrono::Duration;
use diesel::connection::SimpleConnection;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;

#[derive(Debug)]
pub struct ConnectionOptions {
    pub busy_timeout: Duration,
}

impl ConnectionOptions {
    pub fn apply(&self, conn: &mut SqliteConnection) -> QueryResult<()> {
        conn.batch_execute(&format!(
            r#"
            PRAGMA foreign_keys = ON;
            PRAGMA journal_mode = WAL;
            PRAGMA synchronous = NORMAL;
            PRAGMA wal_autocheckpoint = 1000;
            PRAGMA wal_checkpoint(TRUNCATE);
            PRAGMA busy_timeout = {};
        "#,
            self.busy_timeout.num_milliseconds()
        ))?;

        Ok(())
    }
}

impl Default for ConnectionOptions {
    fn default() -> Self {
        Self {
            busy_timeout: Duration::try_milliseconds(5000).unwrap(),
        }
    }
}

impl diesel::r2d2::CustomizeConnection<SqliteConnection, diesel::r2d2::Error> for ConnectionOptions {
    fn on_acquire(&self, conn: &mut SqliteConnection) -> Result<(), diesel::r2d2::Error> {
        self.apply(conn).map_err(diesel::r2d2::Error::QueryError)
    }
}
