/*
 * asklyphe-frontend routes/semaphore.rs
 * - communication between asklyphe-frontend and asklyphe-auth-frontend
 *
 * Copyright (C) 2025 Real Microsoft, LLC
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use axum::extract::Query;
use axum::response::{IntoResponse, Redirect};
use axum_extra::extract::cookie::{Cookie, Expiration, SameSite};
use axum_extra::extract::CookieJar;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct SemaphoreQuery {
    one_time_token: Option<String>,
}

pub async fn semaphore(
    jar: CookieJar,
    Query(params): Query<SemaphoreQuery>,
) -> impl IntoResponse {
    if params.one_time_token.is_none() {
        return Redirect::to("/").into_response();
    }
    let ott = params.one_time_token.unwrap();
    (jar.add(Cookie::build(("token", ott))
        .permanent()
        .max_age(time::Duration::days(30))
        .secure(true)
        .http_only(true)
        // we can "safely" set lax because anything that could mess up stuff should be behind post requests with tokens
        .same_site(SameSite::Lax)
        .build()
    ), Redirect::to("/")).into_response()
}
