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

namespace Indotalent.Features.Thirdparty.VendorContact.Cqrs;

public class GetVendorContactListResponse
{
    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? VendorName { get; set; }
}

public record GetVendorContactListQuery() : IRequest<List<GetVendorContactListResponse>>;

public class GetVendorContactListHandler : IRequestHandler<GetVendorContactListQuery, List<GetVendorContactListResponse>>
{
    private readonly AppDbContext _context;

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

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