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

namespace Indotalent.Features.Utilities.Todo.Cqrs;

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

public record GetTodoListQuery() : IRequest<List<GetTodoListResponse>>;

public class GetTodoListHandler : IRequestHandler<GetTodoListQuery, List<GetTodoListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetTodoListResponse>> Handle(GetTodoListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Todo
            .AsNoTracking()
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetTodoListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Name = x.Name,
                Description = x.Description,
                StartTime = x.StartTime,
                EndTime = x.EndTime,
                IsCompleted = x.IsCompleted,
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy,
            })
            .ToListAsync(cancellationToken);
    }
}