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

namespace Indotalent.Features.Thirdparty.Customer.Cqrs;

public class GetCustomerListResponse
{
    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? CustomerGroupName { get; set; }
    public string? CustomerCategoryName { get; set; }
}

public record GetCustomerListQuery() : IRequest<List<GetCustomerListResponse>>;

public class GetCustomerListHandler : IRequestHandler<GetCustomerListQuery, List<GetCustomerListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetCustomerListResponse>> Handle(GetCustomerListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Customer
            .AsNoTracking()
            .Include(x => x.CustomerGroup)
            .Include(x => x.CustomerCategory)
            .OrderBy(x => x.Name)
            .Select(x => new GetCustomerListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Name = x.Name,
                PhoneNumber = x.PhoneNumber,
                EmailAddress = x.EmailAddress,
                CustomerGroupName = x.CustomerGroup != null ? x.CustomerGroup.Name : string.Empty,
                CustomerCategoryName = x.CustomerCategory != null ? x.CustomerCategory.Name : string.Empty
            })
            .ToListAsync(cancellationToken);
    }
}