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

namespace Indotalent.Features.Utilities.Todo.Cqrs;

public class CreateTodoRequest
{
    public string? Name { get; set; }
    public string? Description { get; set; }
    public DateTime? StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public bool IsCompleted { get; set; }
}

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

public record CreateTodoCommand(CreateTodoRequest Data) : IRequest<CreateTodoResponse>;

public class CreateTodoHandler : IRequestHandler<CreateTodoCommand, CreateTodoResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateTodoResponse> Handle(CreateTodoCommand 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.Todo
        {
            AutoNumber = autoNo,
            Name = request.Data.Name,
            Description = request.Data.Description,
            StartTime = request.Data.StartTime,
            EndTime = request.Data.EndTime,
            IsCompleted = request.Data.IsCompleted
        };

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

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