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

namespace Indotalent.Features.Utilities.BookingResource.Cqrs;

public class UpdateBookingResourceRequest
{
    public string? Id { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public string? BookingGroupId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateBookingResourceCommand(UpdateBookingResourceRequest Data) : IRequest<UpdateBookingResourceResponse>;

public class UpdateBookingResourceHandler : IRequestHandler<UpdateBookingResourceCommand, UpdateBookingResourceResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<UpdateBookingResourceResponse> Handle(UpdateBookingResourceCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.BookingResource
            .AnyAsync(x => x.Name == request.Data.Name && x.Id != request.Data.Id, cancellationToken);

        if (isExists)
        {
            throw new AlreadyExistsException("Booking Resource", request.Data.Name ?? string.Empty);
        }

        var entity = await _context.BookingResource
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

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

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

        await _context.SaveChangesAsync(cancellationToken);

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