using Microsoft.AspNetCore.Http.HttpResults;
using WorkClub.Api.Services;
using WorkClub.Application.Members.DTOs;

namespace WorkClub.Api.Endpoints.Members;

public static class MemberEndpoints
{
    public static void MapMemberEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/members");

        group.MapGet("", GetMembers)
            .RequireAuthorization("RequireMember")
            .WithName("GetMembers");

        group.MapGet("{id:guid}", GetMemberById)
            .RequireAuthorization("RequireMember")
            .WithName("GetMemberById");

        group.MapGet("/me", GetCurrentMember)
            .RequireAuthorization("RequireMember")
            .WithName("GetCurrentMember");
    }

    private static async Task<Ok<List<MemberListDto>>> GetMembers(MemberService memberService)
    {
        var result = await memberService.GetMembersAsync();
        return TypedResults.Ok(result);
    }

    private static async Task<Results<Ok<MemberDetailDto>, NotFound>> GetMemberById(
        Guid id,
        MemberService memberService)
    {
        var result = await memberService.GetMemberByIdAsync(id);

        if (result == null)
            return TypedResults.NotFound();

        return TypedResults.Ok(result);
    }

    private static async Task<Results<Ok<MemberDetailDto>, NotFound>> GetCurrentMember(MemberService memberService)
    {
        var result = await memberService.GetCurrentMemberAsync();

        if (result == null)
            return TypedResults.NotFound();

        return TypedResults.Ok(result);
    }
}
