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

namespace Indotalent.Features.Utilities.Todo.Cqrs;

public class TodoItemResponse
{
    public string? Id { 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 GetTodoByIdResponse
{
    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 List<TodoItemResponse> TodoItems { get; set; } = new List<TodoItemResponse>();
}

public record GetTodoByIdQuery(string Id) : IRequest<GetTodoByIdResponse?>;

public class GetTodoByIdHandler : IRequestHandler<GetTodoByIdQuery, GetTodoByIdResponse?>
{
    private readonly AppDbContext _context;

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

    public async Task<GetTodoByIdResponse?> Handle(GetTodoByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Todo
            .AsNoTracking()
            .Include(x => x.TodoItemList)
            .Where(x => x.Id == request.Id)
            .Select(x => new GetTodoByIdResponse
            {
                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,
                TodoItems = x.TodoItemList
                    .OrderBy(i => i.StartTime)
                    .Select(i => new TodoItemResponse
                    {
                        Id = i.Id,
                        Name = i.Name,
                        Description = i.Description,
                        StartTime = i.StartTime,
                        EndTime = i.EndTime,
                        IsCompleted = i.IsCompleted
                    }).ToList()
            })
            .FirstOrDefaultAsync(cancellationToken);
    }
}