using Indotalent.Infrastructure.Database;
using MediatR;

namespace Indotalent.Features.Utilities.Todo.Cqrs;

public class CreateTodoItemRequest
{
    public string? TodoId { get; set; }
    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 CreateTodoItemResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateTodoItemCommand(CreateTodoItemRequest Data) : IRequest<CreateTodoItemResponse>;

public class CreateTodoItemHandler : IRequestHandler<CreateTodoItemCommand, CreateTodoItemResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateTodoItemResponse> Handle(CreateTodoItemCommand request, CancellationToken cancellationToken)
    {
        var entity = new Data.Entities.TodoItem
        {
            TodoId = request.Data.TodoId,
            Name = request.Data.Name,
            Description = request.Data.Description,
            StartTime = request.Data.StartTime,
            EndTime = request.Data.EndTime,
            IsCompleted = request.Data.IsCompleted
        };

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

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