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

namespace Indotalent.Features.Pipeline.Expense.Cqrs;

public class GetExpenseByIdResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Title { get; set; }
    public string? Description { get; set; }
    public DateTime? ExpenseDate { get; set; }
    public Data.Enums.ExpenseStatus Status { get; set; }
    public decimal? Amount { get; set; }
    public string? CampaignId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record GetExpenseByIdQuery(string Id) : IRequest<GetExpenseByIdResponse?>;

public class GetExpenseByIdHandler : IRequestHandler<GetExpenseByIdQuery, GetExpenseByIdResponse?>
{
    private readonly AppDbContext _context;

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

    public async Task<GetExpenseByIdResponse?> Handle(GetExpenseByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Expense
            .AsNoTracking()
            .Where(x => x.Id == request.Id)
            .Select(x => new GetExpenseByIdResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Title = x.Title,
                Description = x.Description,
                ExpenseDate = x.ExpenseDate,
                Status = x.Status,
                Amount = x.Amount,
                CampaignId = x.CampaignId,
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy
            })
            .FirstOrDefaultAsync(cancellationToken);
    }
}