use rocket_sync_db_pools::database;
use serde::Serialize;
use diesel::prelude::*;

use crate::schema::uploads;
use crate::lib;


#[database("punt")]
pub struct DbConn(diesel::SqliteConnection);


#[derive(Queryable, Insertable, Serialize)]
#[table_name="uploads"]
pub struct FileInfo {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub created_at: Option<i64> // figure out how to marshal this to a proper time type later
}


pub async fn get_file_info(id: String, conn: DbConn) -> QueryResult<FileInfo> {
    conn.run(|c| uploads::table.find(id).first(c)).await
}


pub async fn put_file_info(id: &str, name: Option<&str>, conn: DbConn) -> QueryResult<()> {
    let file_info = FileInfo {
        id: id.to_owned(),
        name: name.map(|n| n.to_owned()),
        created_at: Some(lib::timestamp()),
    };

    conn.run(|c| {
        diesel::insert_into(uploads::table)
            .values(file_info)
            .execute(c)
    }).await?;

    Ok(())
}