using Indotalent.Data.Entities;
using Indotalent.Infrastructure.File;
using MediatR;
using Microsoft.AspNetCore.Identity;

namespace Indotalent.Features.Profile.Avatar.Cqrs;

public class ChangeAvatarRequest
{
    public string UserId { get; set; } = string.Empty;
    public byte[] FileData { get; set; } = Array.Empty<byte>();
    public string FileName { get; set; } = string.Empty;
}

public class ChangeAvatarResponse
{
    public bool IsSuccess { get; set; }
    public string Message { get; set; } = string.Empty;
}

public record ChangeAvatarCommand(ChangeAvatarRequest Data) : IRequest<ChangeAvatarResponse>;

public class ChangeAvatarHandler : IRequestHandler<ChangeAvatarCommand, ChangeAvatarResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly FileStorageService _fileStorage;

    public ChangeAvatarHandler(UserManager<ApplicationUser> userManager, FileStorageService fileStorage)
    {
        _userManager = userManager;
        _fileStorage = fileStorage;
    }

    public async Task<ChangeAvatarResponse> Handle(ChangeAvatarCommand request, CancellationToken cancellationToken)
    {
        var user = await _userManager.FindByIdAsync(request.Data.UserId);
        if (user == null) return new ChangeAvatarResponse { IsSuccess = false, Message = "User not found" };

        try
        {
            var extension = Path.GetExtension(request.Data.FileName);

            if (!string.IsNullOrEmpty(user.AvatarFile))
            {
                _fileStorage.DeleteOldAvatar(user.AvatarFile);
            }

            var newFileName = await _fileStorage.SaveAvatarAsync(user.Id, request.Data.FileData, extension);

            user.AvatarFile = newFileName;
            user.UpdatedAt = DateTime.Now;

            var result = await _userManager.UpdateAsync(user);

            return new ChangeAvatarResponse
            {
                IsSuccess = result.Succeeded,
                Message = result.Succeeded ? "Avatar updated successfully" : "Failed to update user profile"
            };
        }
        catch (Exception ex)
        {
            return new ChangeAvatarResponse { IsSuccess = false, Message = ex.Message };
        }
    }
}