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

namespace Indotalent.Features.Pipeline.Expense.Cqrs;

public class GetExpenseListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Title { get; set; }
    public string? CampaignTitle { get; set; }
    public decimal? Amount { get; set; }
    public DateTime? ExpenseDate { get; set; }
    public Data.Enums.ExpenseStatus Status { get; set; }
}

public record GetExpenseListQuery() : IRequest<List<GetExpenseListResponse>>;

public class GetExpenseListHandler : IRequestHandler<GetExpenseListQuery, List<GetExpenseListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetExpenseListResponse>> Handle(GetExpenseListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Expense
            .AsNoTracking()
            .Include(x => x.Campaign)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetExpenseListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Title = x.Title,
                CampaignTitle = x.Campaign != null ? x.Campaign.Title : string.Empty,
                Amount = x.Amount,
                ExpenseDate = x.ExpenseDate,
                Status = x.Status
            })
            .ToListAsync(cancellationToken);
    }
}