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

namespace Indotalent.Features.Sales.CreditNote.Cqrs;

public class CreditNoteLookupResponse
{
    public List<LookupItem> SalesReturns { 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 GetCreditNoteLookupQuery() : IRequest<CreditNoteLookupResponse>;

public class GetCreditNoteLookupHandler : IRequestHandler<GetCreditNoteLookupQuery, CreditNoteLookupResponse>
{
    private readonly AppDbContext _context;
    public GetCreditNoteLookupHandler(AppDbContext context) => _context = context;

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

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

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

        return response;
    }
}