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

namespace Indotalent.Features.Pipeline.Budget.Cqrs;

public class GetBudgetListResponse
{
    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? BudgetDate { get; set; }
    public BudgetStatus Status { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
}

public record GetBudgetListQuery() : IRequest<List<GetBudgetListResponse>>;

public class GetBudgetListHandler : IRequestHandler<GetBudgetListQuery, List<GetBudgetListResponse>>
{
    private readonly AppDbContext _context;

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

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