use anyhow::Result;
use dialtone_common::authz::user_authz_info::UserAuthzInfo;
use sqlx::types::chrono::{DateTime, Utc};
use sqlx::{Executor, Postgres};
use crate::db::return_optional;
pub async fn fetch_auth_and_mark_seen(
exec: impl Executor<'_, Database = Postgres>,
acct: &str,
seen_from: &str,
seen_at: DateTime<Utc>,
) -> Result<Option<UserAuthzInfo>, sqlx::Error> {
let result = sqlx::query(
r#"
with scheck as (
select
json_build_object(
'acct', acct,
'system_permissions', system_permissions,
'status', status
) as authz_info
from user_principal
where
acct = $1
)
update user_principal
set last_seen_data =
jsonb_path_query_array(
jsonb_build_object('from', $2::text, 'at', $3::text)
|| last_seen_data, '$[0 to 10]')
from scheck
where
acct = $1
returning scheck.authz_info as "authz_info: Json<UserPrincipalAuthzInfo>"
"#,
)
.bind(acct)
.bind(seen_from)
.bind(seen_at.to_string())
.fetch_optional(exec)
.await?;
return_optional(&result)
}