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

namespace Indotalent.Features.Utilities.BookingResource.Cqrs;

public class CreateBookingResourceRequest
{
    public string? Name { get; set; }
    public string? Description { get; set; }
    public string? BookingGroupId { get; set; }
}

public class CreateBookingResourceResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateBookingResourceCommand(CreateBookingResourceRequest Data) : IRequest<CreateBookingResourceResponse>;

public class CreateBookingResourceHandler : IRequestHandler<CreateBookingResourceCommand, CreateBookingResourceResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateBookingResourceResponse> Handle(CreateBookingResourceCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.BookingResource
            .AnyAsync(x => x.Name == request.Data.Name, cancellationToken);

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

        var entity = new Data.Entities.BookingResource
        {
            Name = request.Data.Name,
            Description = request.Data.Description,
            BookingGroupId = request.Data.BookingGroupId
        };

        _context.BookingResource.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreateBookingResourceResponse
        {
            Id = entity.Id,
            Name = entity.Name
        };
    }
}