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

namespace Indotalent.Features.Utilities.BookingManager.Cqrs;

public class UpdateBookingRequest
{
    public string? Id { get; set; }
    public string? Subject { get; set; }
    public DateTime? StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public string? StartTimezone { get; set; }
    public string? EndTimezone { get; set; }
    public string? Location { get; set; }
    public string? Description { get; set; }
    public bool? IsAllDay { get; set; }
    public bool? IsReadOnly { get; set; }
    public bool? IsBlock { get; set; }
    public string? RecurrenceRule { get; set; }
    public BookingStatus Status { get; set; }
    public string? BookingResourceId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateBookingCommand(UpdateBookingRequest Data) : IRequest<UpdateBookingResponse>;

public class UpdateBookingHandler : IRequestHandler<UpdateBookingCommand, UpdateBookingResponse>
{
    private readonly AppDbContext _context;

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

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

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

        entity.Subject = request.Data.Subject;
        entity.StartTime = request.Data.StartTime;
        entity.EndTime = request.Data.EndTime;
        entity.StartTimezone = request.Data.StartTimezone;
        entity.EndTimezone = request.Data.EndTimezone;
        entity.Location = request.Data.Location;
        entity.Description = request.Data.Description;
        entity.IsAllDay = request.Data.IsAllDay;
        entity.IsReadOnly = request.Data.IsReadOnly;
        entity.IsBlock = request.Data.IsBlock;
        entity.RecurrenceRule = request.Data.RecurrenceRule;
        entity.Status = request.Data.Status;
        entity.BookingResourceId = request.Data.BookingResourceId;

        await _context.SaveChangesAsync(cancellationToken);

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