// Generated by openapi-moonbit — DO NOT EDIT
// Spec SHA-256: 7e574664c0f434e52021e12f313a3266fd3175fe2ecddde4c0e0930549c72ba2

///|
/// Response wrapper including declared response headers.
#derive(Debug, Eq)
pub(all) struct SubmitOauth2WebflowCallbackResponse {
  /// Decoded response body.
  body : @model.Empty
  /// Response header `LOCATION`.
  location : String
}

///|
/// Success responses for `poll_oauth2_webflow`.
#derive(Debug, Eq)
pub(all) enum PollOauth2WebflowResult {
  /// OAuth flow has completed
  Status200(@model.TokenWithSecret)
  /// OAuth flow is pending
  Status202(@model.Empty)
}

///|
/// Operations in the `Login` group. Implement this trait to mock or wrap `Client`.
pub(open) trait LoginClient {
  async fn login_oauth2(self : Self, body~ : @model.OAuth2Login) -> @model.TokenWithSecret raise GolemError
  async fn start_oauth2_webflow(self : Self, body~ : @model.OAuth2WebflowStart) -> @model.OAuth2WebflowData raise GolemError
  async fn submit_oauth2_webflow_callback(
    self : Self,
    code~ : String,
    state~ : @uuid.UUID,
  ) -> SubmitOauth2WebflowCallbackResponse raise GolemError
  async fn poll_oauth2_webflow(self : Self, state~ : @uuid.UUID) -> PollOauth2WebflowResult raise GolemError
}

///|
/// Acquire token with OAuth2 authorization
/// Gets a token by authorizing with an external OAuth2 provider. Currently only github is supported.
///
/// In the response:
/// - `id` is the identifier of the token itself
/// - `accountId` is the account's identifier, can be used on the account API
/// - `secret` is the secret key to be sent in the Authorization header as a bearer token for all the other endpoints
///
/// `POST /v1/login/oauth2` (`login_oauth2`).
pub impl[T : @runtime.Transport] LoginClient for Client[T] with fn login_oauth2(
  self : Client[T],
  body~ : @model.OAuth2Login,
) -> @model.TokenWithSecret raise GolemError {
  let __path = "/v1/login/oauth2"
  let __req = self.prepare_request(
    http_method="POST",
    path=__path,
    apply_auth=false,
  )
  let _ = __req.with_body(
    content_type="application/json",
    body=@runtime.utf8_encode(body.to_json().stringify()),
  )
  let __resp = self.send_request(__req)
  match __resp.status() {
    200 =>
      self.decode_json_response(__resp, __r => {
        (
          @cjson.FromJson::from_json(__r.raw(), __r.context()) :
          @model.TokenWithSecret)
      })
    _ => raise self.api_error_from_response(__resp)
  }
}

///|
/// Initiate OAuth2 Web Flow
/// Starts the OAuth2 web flow. Two flow kinds are supported:
///
/// - `browser`: The callback will immediately redirect to the given URL with the
/// Golem token secret appended as a `token` query parameter. Intended for
/// browser-based frontends.
///
/// - `cli`: The callback stores the token in the session. The client polls the
/// poll endpoint with the returned state id to retrieve the token once available.
/// Intended for CLI tools and headless environments.
///
/// `POST /v1/login/oauth2/web/authorize` (`start_oauth2_webflow`).
pub impl[T : @runtime.Transport] LoginClient for Client[T] with fn start_oauth2_webflow(
  self : Client[T],
  body~ : @model.OAuth2WebflowStart,
) -> @model.OAuth2WebflowData raise GolemError {
  let __path = "/v1/login/oauth2/web/authorize"
  let __req = self.prepare_request(
    http_method="POST",
    path=__path,
    apply_auth=false,
  )
  let _ = __req.with_body(
    content_type="application/json",
    body=@runtime.utf8_encode(body.to_json().stringify()),
  )
  let __resp = self.send_request(__req)
  match __resp.status() {
    200 =>
      self.decode_json_response(__resp, __r => {
        (
          @cjson.FromJson::from_json(__r.raw(), __r.context()) :
          @model.OAuth2WebflowData)
      })
    _ => raise self.api_error_from_response(__resp)
  }
}

///|
/// OAuth2 Web Flow callback
/// This endpoint handles the callback from the provider after the user has authorized the application.
/// It exchanges the code for an access token and then uses that to log the user in.
///
/// `GET /v1/login/oauth2/web/callback` (`submit_oauth2_webflow_callback`).
pub impl[T : @runtime.Transport] LoginClient for Client[T] with fn submit_oauth2_webflow_callback(
  self : Client[T],
  code~ : String,
  state~ : @uuid.UUID,
) -> SubmitOauth2WebflowCallbackResponse raise GolemError {
  let __path = "/v1/login/oauth2/web/callback"
  let __qb = @encoding.QueryBuilder::new()
  let _ = __qb.add_scalar("code", code)
  let _ = __qb.add_scalar("state", state.to_string())
  let __req = self.prepare_request(
    http_method="GET",
    path=__path,
    query=__qb.build(),
    apply_auth=false,
  )
  let __resp = self.send_request(__req)
  match __resp.status() {
    302 => {
      let body = if __resp.body().is_empty() {
        @cjson.Json::null()
      } else {
        let __b = __resp.text()
        @rjson.parse_json(__b) catch {
          e => {
            let __err = GolemError::Decode(
              status=__resp.status(),
              message=e.to_string(),
              body=__b,
            )
            raise __err
          }
        }
      }
      let __hdrs = __resp.headers()
      let location = match __hdrs.get("LOCATION") {
        Option::Some(__raw_hdr) => __raw_hdr
        Option::None => {
          let __err = GolemError::Decode(
            status=__resp.status(),
            message="missing required response header: " + "LOCATION",
            body=__resp.text(),
          )
          raise __err
        }
      }
      SubmitOauth2WebflowCallbackResponse::{ body, location, }
    }
    _ => raise self.api_error_from_response(__resp)
  }
}

///|
/// Poll for OAuth2 Web Flow token
/// This endpoint is used by clients to poll for the token after the user has authorized the application via the web flow.
/// A given state might only be exchanged for a token once. Any further attempts to exchange the state will fail.
///
/// `GET /v1/login/oauth2/web/poll` (`poll_oauth2_webflow`).
pub impl[T : @runtime.Transport] LoginClient for Client[T] with fn poll_oauth2_webflow(
  self : Client[T],
  state~ : @uuid.UUID,
) -> PollOauth2WebflowResult raise GolemError {
  let __path = "/v1/login/oauth2/web/poll"
  let __qb = @encoding.QueryBuilder::new()
  let _ = __qb.add_scalar("state", state.to_string())
  let __req = self.prepare_request(
    http_method="GET",
    path=__path,
    query=__qb.build(),
    apply_auth=false,
  )
  let __resp = self.send_request(__req)
  match __resp.status() {
    200 =>
      PollOauth2WebflowResult::Status200(
        self.decode_json_response(__resp, __r => {
          (
            @cjson.FromJson::from_json(__r.raw(), __r.context()) :
            @model.TokenWithSecret)
        }),
      )
    202 =>
      PollOauth2WebflowResult::Status202(
        if __resp.body().is_empty() {
          @cjson.Json::null()
        } else {
          let __b = __resp.text()
          @rjson.parse_json(__b) catch {
            e => {
              let __err = GolemError::Decode(
                status=__resp.status(),
                message=e.to_string(),
                body=__b,
              )
              raise __err
            }
          }
        },
      )
    _ => raise self.api_error_from_response(__resp)
  }
}

///|
pub extend Client with LoginClient::{
  login_oauth2,
  start_oauth2_webflow,
  submit_oauth2_webflow_callback,
  poll_oauth2_webflow,
}