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

namespace Indotalent.Features.Purchase.DebitNote.Cqrs;

public class DebitNoteLookupResponse
{
    public List<LookupItem> PurchaseReturns { get; set; } = new();
    public List<LookupStatusItem> Statuses { get; set; } = new();
}

public class LookupItem
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public class LookupStatusItem
{
    public int Value { get; set; }
    public string? Name { get; set; }
}

public record GetDebitNoteLookupQuery() : IRequest<DebitNoteLookupResponse>;

public class GetDebitNoteLookupHandler : IRequestHandler<GetDebitNoteLookupQuery, DebitNoteLookupResponse>
{
    private readonly AppDbContext _context;
    public GetDebitNoteLookupHandler(AppDbContext context) => _context = context;

    public async Task<DebitNoteLookupResponse> Handle(GetDebitNoteLookupQuery request, CancellationToken cancellationToken)
    {
        var response = new DebitNoteLookupResponse();

        response.PurchaseReturns = await _context.PurchaseReturn.AsNoTracking()
            .Where(x => x.Status == PurchaseReturnStatus.Confirmed)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new LookupItem { Id = x.Id, Name = x.AutoNumber })
            .ToListAsync(cancellationToken);

        response.Statuses = Enum.GetValues(typeof(DebitNoteStatus))
            .Cast<DebitNoteStatus>()
            .Select(x => new LookupStatusItem
            {
                Value = (int)x,
                Name = x.GetDescription()
            }).ToList();

        return response;
    }
}