use crate::storage::Error;
use crate::storage::config_store::adapters::postgres::schema::Table;
use sqlx::{Pool, Postgres};

pub(super) async fn perform(
    pool: &Pool<Postgres>,
    table: &Table,
    id: &str,
    by_account_id: Option<String>,
) -> Result<(), Error> {
    // Prepare query
    let sql = {
        let table_name = &table.name;
        format!("UPDATE {table_name} SET deleted_at = NOW(), deleted_by_account_id = $1 WHERE id = $2")
    };
    log::debug!(sql; "Deleting one");

    // Perform query
    let res = sqlx::query(&sql)
        .bind(by_account_id)
        .bind(id)
        .execute(pool)
        .await
        .map_err(|e| Error::internal(e.to_string()))?;
    if res.rows_affected() < 1 {
        return Err(Error::not_found("No such record"));
    }

    Ok(())
}
