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

namespace Indotalent.Features.Pipeline.SalesRepresentative.Cqrs;

public class GetSalesRepresentativeListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Name { get; set; }
    public string? JobTitle { get; set; }
    public string? EmployeeNumber { get; set; }
    public string? PhoneNumber { get; set; }
    public string? EmailAddress { get; set; }
    public string? SalesTeamName { get; set; }
}

public record GetSalesRepresentativeListQuery() : IRequest<List<GetSalesRepresentativeListResponse>>;

public class GetSalesRepresentativeListHandler : IRequestHandler<GetSalesRepresentativeListQuery, List<GetSalesRepresentativeListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetSalesRepresentativeListResponse>> Handle(GetSalesRepresentativeListQuery request, CancellationToken cancellationToken)
    {
        return await _context.SalesRepresentative
            .AsNoTracking()
            .Include(x => x.SalesTeam)
            .OrderBy(x => x.Name)
            .Select(x => new GetSalesRepresentativeListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Name = x.Name,
                JobTitle = x.JobTitle,
                EmployeeNumber = x.EmployeeNumber,
                PhoneNumber = x.PhoneNumber,
                EmailAddress = x.EmailAddress,
                SalesTeamName = x.SalesTeam != null ? x.SalesTeam.Name : string.Empty
            })
            .ToListAsync(cancellationToken);
    }
}