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

namespace Indotalent.Features.Thirdparty.Vendor.Cqrs;

public class GetVendorListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Name { get; set; }
    public string? PhoneNumber { get; set; }
    public string? EmailAddress { get; set; }
    public string? VendorGroupName { get; set; }
    public string? VendorCategoryName { get; set; }
}

public record GetVendorListQuery() : IRequest<List<GetVendorListResponse>>;

public class GetVendorListHandler : IRequestHandler<GetVendorListQuery, List<GetVendorListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetVendorListResponse>> Handle(GetVendorListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Vendor
            .AsNoTracking()
            .Include(x => x.VendorGroup)
            .Include(x => x.VendorCategory)
            .OrderBy(x => x.Name)
            .Select(x => new GetVendorListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Name = x.Name,
                PhoneNumber = x.PhoneNumber,
                EmailAddress = x.EmailAddress,
                VendorGroupName = x.VendorGroup != null ? x.VendorGroup.Name : string.Empty,
                VendorCategoryName = x.VendorCategory != null ? x.VendorCategory.Name : string.Empty
            })
            .ToListAsync(cancellationToken);
    }
}