using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Infrastructure.Database;
using MediatR;
using Indotalent.Data.Enums;

namespace Indotalent.Features.Utilities.BookingManager.Cqrs;

public class CreateBookingRequest
{
    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 class CreateBookingResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
}

public record CreateBookingCommand(CreateBookingRequest Data) : IRequest<CreateBookingResponse>;

public class CreateBookingHandler : IRequestHandler<CreateBookingCommand, CreateBookingResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateBookingResponse> Handle(CreateBookingCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.Booking);

        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.Booking
        {
            AutoNumber = autoNo,
            Subject = request.Data.Subject,
            StartTime = request.Data.StartTime,
            EndTime = request.Data.EndTime,
            StartTimezone = request.Data.StartTimezone,
            EndTimezone = request.Data.EndTimezone,
            Location = request.Data.Location,
            Description = request.Data.Description,
            IsAllDay = request.Data.IsAllDay,
            IsReadOnly = request.Data.IsReadOnly,
            IsBlock = request.Data.IsBlock,
            RecurrenceRule = request.Data.RecurrenceRule,
            Status = request.Data.Status,
            BookingResourceId = request.Data.BookingResourceId
        };

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

        return new CreateBookingResponse
        {
            Id = entity.Id,
            AutoNumber = entity.AutoNumber
        };
    }
}