using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Profile.Avatar.Cqrs;
using Indotalent.Infrastructure.File;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;

namespace Indotalent.Features.Profile.Avatar;

public static class AvatarEndpoint
{
    public static void MapAvatarEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/profile-avatar").WithTags("Profile Avatar")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

        group.MapGet("/info/{userId}", async (string userId, IMediator mediator) =>
        {
            var result = await mediator.Send(new GetAvatarInfoQuery(userId));
            return result.ToApiResponse("Avatar info retrieved successfully");
        })
        .WithName("GetMyAvatarInfo");

        group.MapPost("/change", async (ChangeAvatarRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new ChangeAvatarCommand(request));
            return result.IsSuccess
                ? result.ToApiResponse(result.Message)
                : result.ToApiResponse(result.Message, StatusCodes.Status400BadRequest);
        })
        .WithName("ProfileChangeAvatar");

        group.MapGet("/avatar-image/{fileName}", async (string fileName, IOptions<FileStorageSettingsModel> options, IWebHostEnvironment env) =>
        {
            var avatarSettings = options.Value.Avatar;
            var folderPath = Path.Combine(env.WebRootPath, avatarSettings.StoragePath);
            var filePath = Path.Combine(folderPath, fileName);

            if (!System.IO.File.Exists(filePath)) return Results.NotFound();

            var bytes = await System.IO.File.ReadAllBytesAsync(filePath);
            var extension = Path.GetExtension(fileName).ToLower();
            var contentType = extension switch
            {
                ".png" => "image/png",
                ".jpg" or ".jpeg" => "image/jpeg",
                _ => "application/octet-stream"
            };
            return Results.File(bytes, contentType);
        })
        .WithName("ProfileGetAvatarImage");
    }
}