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

namespace Indotalent.Features.Purchase.DebitNote.Cqrs;

public class GetDebitNoteListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? DebitNoteDate { get; set; }
    public string? PurchaseReturnNumber { get; set; }
    public string? VendorName { get; set; }
    public Data.Enums.DebitNoteStatus DebitNoteStatus { get; set; }
}

public record GetDebitNoteListQuery() : IRequest<List<GetDebitNoteListResponse>>;

public class GetDebitNoteListHandler : IRequestHandler<GetDebitNoteListQuery, List<GetDebitNoteListResponse>>
{
    private readonly AppDbContext _context;
    public GetDebitNoteListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetDebitNoteListResponse>> Handle(GetDebitNoteListQuery request, CancellationToken cancellationToken)
    {
        return await _context.DebitNote
            .AsNoTracking()
            .Include(x => x.PurchaseReturn)
                .ThenInclude(pr => pr!.GoodsReceive)
                    .ThenInclude(gr => gr!.PurchaseOrder)
                        .ThenInclude(po => po!.Vendor)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetDebitNoteListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                DebitNoteDate = x.DebitNoteDate,
                PurchaseReturnNumber = x.PurchaseReturn!.AutoNumber,
                VendorName = x.PurchaseReturn!.GoodsReceive!.PurchaseOrder!.Vendor!.Name,
                DebitNoteStatus = x.DebitNoteStatus
            }).ToListAsync(cancellationToken);
    }
}