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

namespace Indotalent.Features.Sales.CreditNote.Cqrs;

public class GetCreditNoteListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? CreditNoteDate { get; set; }
    public string? SalesReturnNumber { get; set; }
    public string? CustomerName { get; set; }
    public Data.Enums.CreditNoteStatus CreditNoteStatus { get; set; }
}

public record GetCreditNoteListQuery() : IRequest<List<GetCreditNoteListResponse>>;

public class GetCreditNoteListHandler : IRequestHandler<GetCreditNoteListQuery, List<GetCreditNoteListResponse>>
{
    private readonly AppDbContext _context;
    public GetCreditNoteListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetCreditNoteListResponse>> Handle(GetCreditNoteListQuery request, CancellationToken cancellationToken)
    {
        return await _context.CreditNote
            .AsNoTracking()
            .Include(x => x.SalesReturn)
                .ThenInclude(sr => sr!.DeliveryOrder)
                    .ThenInclude(do_ => do_!.SalesOrder)
                        .ThenInclude(so => so!.Customer)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetCreditNoteListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                CreditNoteDate = x.CreditNoteDate,
                SalesReturnNumber = x.SalesReturn!.AutoNumber,
                CustomerName = x.SalesReturn!.DeliveryOrder!.SalesOrder!.Customer!.Name,
                CreditNoteStatus = x.CreditNoteStatus
            }).ToListAsync(cancellationToken);
    }
}