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

namespace WorkClub.Api.Endpoints.Clubs;

public static class AdminClubEndpoints
{
    public static void MapAdminClubEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/admin/clubs")
            .RequireAuthorization("RequireGlobalAdmin")
            .WithTags("AdminClubs");

        group.MapGet("", GetClubs)
            .WithName("AdminGetClubs");

        group.MapPost("", CreateClub)
            .WithName("AdminCreateClub");

        group.MapPut("{id:guid}", UpdateClub)
            .WithName("AdminUpdateClub");

        group.MapDelete("{id:guid}", DeleteClub)
            .WithName("AdminDeleteClub");
    }

    private static async Task<Ok<List<ClubDetailDto>>> GetClubs(AdminClubService adminClubService)
    {
        var result = await adminClubService.GetAllClubsAsync();
        return TypedResults.Ok(result);
    }

    private static async Task<Created<ClubDetailDto>> CreateClub(
        [FromBody] CreateClubRequest request,
        AdminClubService adminClubService)
    {
        var result = await adminClubService.CreateClubAsync(request);
        return TypedResults.Created($"/api/admin/clubs/{result.Id}", result);
    }

    private static async Task<Results<Ok<ClubDetailDto>, NotFound>> UpdateClub(
        Guid id,
        [FromBody] UpdateClubRequest request,
        AdminClubService adminClubService)
    {
        var (result, error) = await adminClubService.UpdateClubAsync(id, request);
        
        if (error != null)
            return TypedResults.NotFound();

        return TypedResults.Ok(result!);
    }

    private static async Task<Results<NoContent, NotFound>> DeleteClub(
        Guid id,
        AdminClubService adminClubService)
    {
        var success = await adminClubService.DeleteClubAsync(id);
        
        if (!success)
            return TypedResults.NotFound();

        return TypedResults.NoContent();
    }
}
