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

namespace Indotalent.Features.Utilities.BookingManager.Cqrs;

public class GetBookingListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { 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 DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record GetBookingListQuery() : IRequest<List<GetBookingListResponse>>;

public class GetBookingListHandler : IRequestHandler<GetBookingListQuery, List<GetBookingListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetBookingListResponse>> Handle(GetBookingListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Booking
            .AsNoTracking()
            .Include(x => x.BookingResource)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetBookingListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Subject = x.Subject,
                StartTime = x.StartTime,
                EndTime = x.EndTime,
                Status = x.Status.GetDescription(),
                ResourceName = x.BookingResource != null ? x.BookingResource.Name : string.Empty,
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy
            })
            .ToListAsync(cancellationToken);
    }
}