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

namespace Indotalent.Features.Pipeline.Lead.Cqrs;

public class GetLeadListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Title { get; set; }
    public string? CompanyName { get; set; }
    public string? CampaignTitle { get; set; }
    public string? SalesTeamName { get; set; }
    public PipelineStage PipelineStage { get; set; }
    public ClosingStatus ClosingStatus { get; set; }
}

public record GetLeadListQuery() : IRequest<List<GetLeadListResponse>>;

public class GetLeadListHandler : IRequestHandler<GetLeadListQuery, List<GetLeadListResponse>>
{
    private readonly AppDbContext _context;

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

    public async Task<List<GetLeadListResponse>> Handle(GetLeadListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Lead
            .AsNoTracking()
            .Include(x => x.Campaign)
            .Include(x => x.SalesTeam)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetLeadListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Title = x.Title,
                CompanyName = x.CompanyName,
                CampaignTitle = x.Campaign != null ? x.Campaign.Title : string.Empty,
                SalesTeamName = x.SalesTeam != null ? x.SalesTeam.Name : string.Empty,
                PipelineStage = x.PipelineStage,
                ClosingStatus = x.ClosingStatus
            })
            .ToListAsync(cancellationToken);
    }
}