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

namespace Indotalent.Features.Pipeline.SalesTeam.Cqrs;

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

public class GetSalesTeamByIdResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
    public List<SalesRepresentativeItemResponse> Representatives { get; set; } = new();
}

public record GetSalesTeamByIdQuery(string Id) : IRequest<GetSalesTeamByIdResponse?>;

public class GetSalesTeamByIdHandler : IRequestHandler<GetSalesTeamByIdQuery, GetSalesTeamByIdResponse?>
{
    private readonly AppDbContext _context;

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

    public async Task<GetSalesTeamByIdResponse?> Handle(GetSalesTeamByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.SalesTeam
            .AsNoTracking()
            .Include(x => x.SalesRepresentativeList)
            .Where(x => x.Id == request.Id)
            .Select(x => new GetSalesTeamByIdResponse
            {
                Id = x.Id,
                Name = x.Name,
                Description = x.Description,
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy,
                Representatives = x.SalesRepresentativeList
                    .OrderBy(r => r.Name)
                    .Select(r => new SalesRepresentativeItemResponse
                    {
                        Id = r.Id,
                        Name = r.Name,
                        AutoNumber = r.AutoNumber,
                        JobTitle = r.JobTitle,
                        EmployeeNumber = r.EmployeeNumber,
                        PhoneNumber = r.PhoneNumber,
                        EmailAddress = r.EmailAddress,
                        Description = r.Description
                    }).ToList()
            })
            .FirstOrDefaultAsync(cancellationToken);
    }
}