use async_graphql::{Context, Enum, InputObject, Object, ID};
use mas_storage::RepositoryAccess;
use crate::graphql::{
model::{BrowserSession, NodeType},
state::ContextExt,
};
#[derive(Default)]
pub struct BrowserSessionMutations {
_private: (),
}
#[derive(InputObject)]
pub struct EndBrowserSessionInput {
browser_session_id: ID,
}
pub enum EndBrowserSessionPayload {
NotFound,
Ended(Box<mas_data_model::BrowserSession>),
}
#[derive(Enum, Copy, Clone, PartialEq, Eq, Debug)]
enum EndBrowserSessionStatus {
Ended,
NotFound,
}
#[Object]
impl EndBrowserSessionPayload {
async fn status(&self) -> EndBrowserSessionStatus {
match self {
Self::Ended(_) => EndBrowserSessionStatus::Ended,
Self::NotFound => EndBrowserSessionStatus::NotFound,
}
}
async fn browser_session(&self) -> Option<BrowserSession> {
match self {
Self::Ended(session) => Some(BrowserSession(*session.clone())),
Self::NotFound => None,
}
}
}
#[Object]
impl BrowserSessionMutations {
async fn end_browser_session(
&self,
ctx: &Context<'_>,
input: EndBrowserSessionInput,
) -> Result<EndBrowserSessionPayload, async_graphql::Error> {
let state = ctx.state();
let browser_session_id =
NodeType::BrowserSession.extract_ulid(&input.browser_session_id)?;
let requester = ctx.requester();
let mut repo = state.repository().await?;
let clock = state.clock();
let session = repo.browser_session().lookup(browser_session_id).await?;
let Some(session) = session else {
return Ok(EndBrowserSessionPayload::NotFound);
};
if !requester.is_owner_or_admin(&session) {
return Ok(EndBrowserSessionPayload::NotFound);
}
let session = repo.browser_session().finish(&clock, session).await?;
repo.save().await?;
Ok(EndBrowserSessionPayload::Ended(Box::new(session)))
}
}