using ASTRAIN.Api.Data;
using ASTRAIN.Api.Services;
using ASTRAIN.Shared.Responses;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;

namespace ASTRAIN.Api.Endpoints;

/// <summary>
/// Provides user-related endpoints.
/// </summary>
internal static class UserEndpoints
{
    /// <summary>
    /// Registers user routes under the provided route group.
    /// </summary>
    /// <param name="group">The API route group.</param>
    /// <returns>The same route group for chaining.</returns>
    public static RouteGroupBuilder MapUserEndpoints(this RouteGroupBuilder group)
    {
        group.MapGet("/users/ensure", async (string? userId, AppDbContext db, IConfiguration config) =>
            {
                var populateSampleData = config.GetValue("SampleData:Enabled", false);
                var user = await UserProvisioning.EnsureUserAsync(db, userId, populateSampleData);
                return Results.Ok(new EnsureUserResponse(user.Id));
            })
            .WithSummary("Ensure user")
            .WithDescription("Ensures a user exists and returns the user id.");

        group.MapGet("/users/{userId}", async (string userId, AppDbContext db, IConfiguration config) =>
            {
                var populateSampleData = config.GetValue("SampleData:Enabled", false);
                var user = await UserProvisioning.EnsureUserAsync(db, userId, populateSampleData);
                return Results.Ok(new EnsureUserResponse(user.Id));
            })
            .WithSummary("Get user")
            .WithDescription("Returns the user id if it exists, or creates a new user.");

        return group;
    }
}
