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

namespace Indotalent.Features.Utilities.ProgramManager.Cqrs;

public class GetProgramManagerListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Title { get; set; }
    public string? ResourceName { get; set; }
    public string? Status { get; set; }
    public string? Priority { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record GetProgramManagerListQuery() : IRequest<List<GetProgramManagerListResponse>>;

public class GetProgramManagerListHandler : IRequestHandler<GetProgramManagerListQuery, List<GetProgramManagerListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetProgramManagerListResponse>> Handle(GetProgramManagerListQuery request, CancellationToken cancellationToken)
    {
        return await _context.ProgramManager
            .AsNoTracking()
            .Include(x => x.ProgramManagerResource)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetProgramManagerListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Title = x.Title,
                ResourceName = x.ProgramManagerResource != null ? x.ProgramManagerResource.Name : string.Empty,
                Status = x.Status.GetDescription(),
                Priority = x.Priority.GetDescription(),
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy
            })
            .ToListAsync(cancellationToken);
    }
}