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

namespace Indotalent.Features.Utilities.BookingScheduler.Cqrs;

public class GetBookingSchedulerListResponse
{
    public string? Id { get; set; }
    public string? Subject { get; set; }
    public DateTime? StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public string? Status { get; set; }
    public string? ResourceName { get; set; }
    public string? ResourceGroupName { get; set; }
    public string? Description { get; set; }
}

public record GetBookingSchedulerListQuery() : IRequest<List<GetBookingSchedulerListResponse>>;

public class GetBookingSchedulerListHandler : IRequestHandler<GetBookingSchedulerListQuery, List<GetBookingSchedulerListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetBookingSchedulerListResponse>> Handle(GetBookingSchedulerListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Booking
            .AsNoTracking()
            .Include(x => x.BookingResource)
                .ThenInclude(x => x!.BookingGroup)
            .OrderBy(x => x.StartTime)
            .Select(x => new GetBookingSchedulerListResponse
            {
                Id = x.Id,
                Subject = x.Subject,
                StartTime = x.StartTime,
                EndTime = x.EndTime,
                Status = x.Status.GetDescription(),
                ResourceName = x.BookingResource != null ? x.BookingResource.Name : "Unassigned",
                ResourceGroupName = x.BookingResource != null && x.BookingResource.BookingGroup != null
                                    ? x.BookingResource.BookingGroup.Name : "General",
                Description = x.Description
            })
            .ToListAsync(cancellationToken);
    }
}