using Indotalent.Infrastructure.Database;
using Indotalent.Infrastructure.File;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Pipeline.LeadContact.Cqrs;

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

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

public record ChangeLeadContactAvatarCommand(ChangeLeadContactAvatarRequest Data) : IRequest<ChangeLeadContactAvatarResponse>;

public class ChangeLeadContactAvatarHandler : IRequestHandler<ChangeLeadContactAvatarCommand, ChangeLeadContactAvatarResponse>
{
    private readonly AppDbContext _context;
    private readonly FileStorageService _fileStorage;

    public ChangeLeadContactAvatarHandler(AppDbContext context, FileStorageService fileStorage)
    {
        _context = context;
        _fileStorage = fileStorage;
    }

    public async Task<ChangeLeadContactAvatarResponse> Handle(ChangeLeadContactAvatarCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.LeadContact
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null) return new ChangeLeadContactAvatarResponse { IsSuccess = false, Message = "Lead Contact not found" };

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

            if (!string.IsNullOrEmpty(entity.AvatarName))
            {
                _fileStorage.DeleteOldAvatar(entity.AvatarName);
            }

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

            entity.AvatarName = newFileName;
            await _context.SaveChangesAsync(cancellationToken);

            return new ChangeLeadContactAvatarResponse
            {
                IsSuccess = true,
                Message = "Lead Contact avatar updated successfully"
            };
        }
        catch (Exception ex)
        {
            return new ChangeLeadContactAvatarResponse { IsSuccess = false, Message = ex.Message };
        }
    }
}