use tokio_postgres::{Client, NoTls};

use crate::config::GeneralServiceConfig;
use crate::web_file_uploads::render_upload_page;

pub type DbResult<T> = Result<T, Box<dyn std::error::Error>>;

pub async fn connect_db(config: &GeneralServiceConfig) -> DbResult<Client> {
    let mut pg_config = tokio_postgres::Config::new();
    pg_config.host(&config.postgres_host);
    pg_config.dbname(&config.pg_database);
    pg_config.user(&config.postgres_user);

    let (client, connection) = pg_config.connect(NoTls).await?;
    tokio::spawn(async move {
        if let Err(err) = connection.await {
            eprintln!("postgres connection error: {err}");
        }
    });

    Ok(client)
}

pub async fn init_database(config: &GeneralServiceConfig) -> DbResult<()> {
    let client = connect_db(config).await?;

    let create_sql =
        "CREATE TABLE IF NOT EXISTS person (\
            id SERIAL PRIMARY KEY,\
            name TEXT NOT NULL,\
            passcode TEXT NOT NULL\
        )";
    client.execute(create_sql, &[]).await?;

    let create_files_sql =
        "CREATE TABLE IF NOT EXISTS stored_file (\
            id SERIAL PRIMARY KEY,\
            filename TEXT NOT NULL,\
            size BIGINT NOT NULL\
        )";
    client.execute(create_files_sql, &[]).await?;

    tokio::fs::create_dir_all(&config.file_storage).await?;

    Ok(())
}
