using Health.Application.Auth;

namespace Health.WebApi.Endpoints;

public static class AuthEndpoints
{
    public static void MapAuthEndpoints(this WebApplication app)
    {
        app.MapPost("/api/auth/send-sms", async (SendSmsRequest request, IAuthService auth, CancellationToken ct) =>
            ToResult(await auth.SendCodeAsync(request.Phone, app.Environment.IsDevelopment(), ct)));
        app.MapPost("/api/auth/register", async (RegisterRequest request, IAuthService auth, CancellationToken ct) =>
            ToResult(await auth.RegisterAsync(new RegisterCommand(request.Phone, request.SmsCode, request.Name, request.DoctorId), ct)));
        app.MapPost("/api/auth/login", async (LoginRequest request, IAuthService auth, CancellationToken ct) =>
            ToResult(await auth.LoginAsync(request.Phone, request.SmsCode, ct)));
        app.MapPost("/api/auth/refresh", async (RefreshRequest request, IAuthService auth, CancellationToken ct) =>
            ToResult(await auth.RefreshAsync(request.RefreshToken, ct)));
        app.MapPost("/api/auth/logout", async (RefreshRequest request, IAuthService auth, CancellationToken ct) =>
        {
            await auth.LogoutAsync(request.RefreshToken, ct);
            return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
        });
    }

    private static IResult ToResult(AuthResult result) =>
        Results.Ok(new { code = result.Code, data = result.Data, message = result.Message });
}

public sealed record SendSmsRequest(string Phone);
public sealed record RegisterRequest(string Phone, string SmsCode, string Name, Guid DoctorId);
public sealed record LoginRequest(string Phone, string SmsCode);
public sealed record RefreshRequest(string RefreshToken);
