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

namespace Indotalent.Features.Inventory.Product.Cqrs;

public class GetProductListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Name { get; set; }
    public decimal? UnitPrice { get; set; }
    public bool? Physical { get; set; }
    public string? UnitMeasureName { get; set; }
    public string? ProductGroupName { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
}

public record GetProductListQuery() : IRequest<List<GetProductListResponse>>;

public class GetProductListHandler : IRequestHandler<GetProductListQuery, List<GetProductListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetProductListResponse>> Handle(GetProductListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Product
            .AsNoTracking()
            .Include(x => x.UnitMeasure)
            .Include(x => x.ProductGroup)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetProductListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Name = x.Name,
                UnitPrice = x.UnitPrice,
                Physical = x.Physical,
                UnitMeasureName = x.UnitMeasure != null ? x.UnitMeasure.Name : string.Empty,
                ProductGroupName = x.ProductGroup != null ? x.ProductGroup.Name : string.Empty,
                CreatedAt = x.CreatedAt
            })
            .ToListAsync(cancellationToken);
    }
}