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

namespace Indotalent.Features.Utilities.ProgramResource.Cqrs;

public class UpdateProgramResourceRequest
{
    public string? Id { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
}

public class UpdateProgramResourceResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateProgramResourceCommand(UpdateProgramResourceRequest Data) : IRequest<UpdateProgramResourceResponse>;

public class UpdateProgramResourceHandler : IRequestHandler<UpdateProgramResourceCommand, UpdateProgramResourceResponse>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null)
        {
            return new UpdateProgramResourceResponse { Id = request.Data.Id, Success = false };
        }

        entity.Name = request.Data.Name;
        entity.Description = request.Data.Description;

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateProgramResourceResponse
        {
            Id = entity.Id,
            Success = true
        };
    }
}