package de.effigenix.loadtest.scenario;

import de.effigenix.loadtest.util.JsonBodyBuilder;
import io.gatling.javaapi.core.ScenarioBuilder;
import io.gatling.javaapi.http.HttpRequestActionBuilder;

import static io.gatling.javaapi.core.CoreDsl.*;
import static io.gatling.javaapi.http.HttpDsl.*;

/**
 * Authentifizierungs-Szenario: Login → Token extrahieren → Token in Folge-Requests verwenden.
 */
public final class AuthenticationScenario {

    private AuthenticationScenario() {}

    /**
     * Login-Request der ein JWT-Token extrahiert und in der Session speichert.
     */
    public static HttpRequestActionBuilder login(String username, String password) {
        return http("Login [" + username + "]")
                .post("/api/auth/login")
                .header("Content-Type", "application/json")
                .body(StringBody(JsonBodyBuilder.loginBody(username, password)))
                .check(
                        status().is(200),
                        jsonPath("$.accessToken").saveAs("accessToken"),
                        jsonPath("$.refreshToken").saveAs("refreshToken")
                );
    }

    /**
     * Token-Refresh-Request.
     */
    public static HttpRequestActionBuilder refreshToken() {
        return http("Token Refresh")
                .post("/api/auth/refresh")
                .header("Content-Type", "application/json")
                .body(StringBody("""
                        {"refreshToken":"#{refreshToken}"}"""))
                .check(
                        status().is(200),
                        jsonPath("$.accessToken").saveAs("accessToken"),
                        jsonPath("$.refreshToken").saveAs("refreshToken")
                );
    }

    /**
     * Vollständiges Auth-Szenario: Login → Pause → Refresh → Pause → Logout.
     */
    public static ScenarioBuilder authWorkflow() {
        return scenario("Authentication Workflow")
                .exec(login("admin", "admin123"))
                .pause(1, 3)
                .exec(refreshToken())
                .pause(1, 2)
                .exec(
                        http("Logout")
                                .post("/api/auth/logout")
                                .header("Authorization", "Bearer #{accessToken}")
                                .check(status().in(200, 204))
                );
    }
}
