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

namespace Indotalent.Features.Thirdparty.CustomerContact.Cqrs;

public class GetCustomerContactListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Name { get; set; }
    public string? JobTitle { get; set; }
    public string? PhoneNumber { get; set; }
    public string? EmailAddress { get; set; }
    public string? CustomerName { get; set; }
}

public record GetCustomerContactListQuery() : IRequest<List<GetCustomerContactListResponse>>;

public class GetCustomerContactListHandler : IRequestHandler<GetCustomerContactListQuery, List<GetCustomerContactListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetCustomerContactListResponse>> Handle(GetCustomerContactListQuery request, CancellationToken cancellationToken)
    {
        return await _context.CustomerContact
            .AsNoTracking()
            .Include(x => x.Customer)
            .OrderBy(x => x.Name)
            .Select(x => new GetCustomerContactListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Name = x.Name,
                JobTitle = x.JobTitle,
                PhoneNumber = x.PhoneNumber,
                EmailAddress = x.EmailAddress,
                CustomerName = x.Customer != null ? x.Customer.Name : string.Empty
            })
            .ToListAsync(cancellationToken);
    }
}