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

namespace Indotalent.Features.Setting.SystemUser;

public static class SystemUserEndpoint
{
    public static void MapSystemUserEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/system-user").WithTags("SystemUsers")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

        group.MapGet("/", async (IMediator mediator) =>
        {
            var result = await mediator.Send(new GetSystemUserListQuery());
            return result.ToApiResponse("User list retrieved successfully");
        })
        .WithName("GetSystemUserList");

        group.MapGet("/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new GetSystemUserByIdQuery(id));
            return result.ToApiResponse(result is not null ? "User detail retrieved" : "User not found");
        })
        .WithName("GetSystemUserById");

        group.MapPost("/", async (CreateSystemUserRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new CreateSystemUserCommand(request));
            return result.ToApiResponse("User created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateSystemUser");

        group.MapPost("/update", async (UpdateSystemUserRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new UpdateSystemUserCommand(request));
            return result.Success
                ? result.ToApiResponse("User updated successfully")
                : ((object?)null).ToApiResponse("Update failed");
        })
        .WithName("UpdateSystemUser");

        group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new DeleteSystemUserByIdCommand(new DeleteSystemUserByIdRequest(id)));
            return result.ToApiResponse("User deleted successfully");
        })
        .WithName("DeleteSystemUserById");

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

        group.MapPost("/send-reset-link/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new AdminForgotPasswordCommand(id));
            return result.IsSuccess
                ? result.ToApiResponse(result.Message)
                : result.ToApiResponse(result.Message, StatusCodes.Status400BadRequest);
        })
        .WithName("AdminSendResetLink");

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

        group.MapPost("/change-avatar", 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("ChangeAvatar");

        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("GetAvatarImage");

    }
}