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

namespace Indotalent.Features.Utilities.Todo.Cqrs;

public class DeleteTodoByIdRequest
{
    public DeleteTodoByIdRequest(string id) => Id = id;
    public string Id { get; set; }
}

public record DeleteTodoByIdCommand(DeleteTodoByIdRequest Data) : IRequest<bool>;

public class DeleteTodoByIdHandler : IRequestHandler<DeleteTodoByIdCommand, bool>
{
    private readonly AppDbContext _context;

    public DeleteTodoByIdHandler(AppDbContext context) => _context = context;

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

        if (entity == null)
        {
            return false;
        }

        _context.Todo.Remove(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}