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

namespace Indotalent.Features.Pipeline.Campaign.Cqrs;

public class GetCampaignListResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public string? Title { get; set; }
    public string? SalesTeamName { get; set; }
    public DateTime? CampaignDateStart { get; set; }
    public string? Status { get; set; }
    public decimal? TargetRevenueAmount { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record GetCampaignListQuery() : IRequest<List<GetCampaignListResponse>>;

public class GetCampaignListHandler : IRequestHandler<GetCampaignListQuery, List<GetCampaignListResponse>>
{
    private readonly AppDbContext _context;
    public GetCampaignListHandler(AppDbContext context) => _context = context;

    public async Task<List<GetCampaignListResponse>> Handle(GetCampaignListQuery request, CancellationToken cancellationToken)
    {
        return await _context.Campaign
            .AsNoTracking()
            .Include(x => x.SalesTeam)
            .OrderByDescending(x => x.CreatedAt)
            .Select(x => new GetCampaignListResponse
            {
                Id = x.Id,
                AutoNumber = x.AutoNumber,
                Title = x.Title,
                SalesTeamName = x.SalesTeam != null ? x.SalesTeam.Name : string.Empty,
                CampaignDateStart = x.CampaignDateStart,
                Status = x.Status.GetDescription(),
                TargetRevenueAmount = x.TargetRevenueAmount,
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy
            }).ToListAsync(cancellationToken);
    }
}