using MediatR;
using Microsoft.EntityFrameworkCore;
using AdsAnalyticsService.API.Application.DTOs;
using AdsAnalyticsService.Infrastructure;

namespace AdsAnalyticsService.API.Application.Queries;

/// <summary>
/// EN: Query to get list of reports for an advertiser.
/// VI: Query lấy danh sách báo cáo cho advertiser.
/// </summary>
public record GetReportsQuery : IRequest<List<ReportListDto>>
{
    public Guid AdvertiserId { get; init; }
    public int Skip { get; init; } = 0;
    public int Take { get; init; } = 20;
}

/// <summary>
/// EN: Handler for GetReportsQuery.
/// VI: Handler cho GetReportsQuery.
/// </summary>
public class GetReportsQueryHandler : IRequestHandler<GetReportsQuery, List<ReportListDto>>
{
    private readonly AdsAnalyticsServiceContext _context;

    public GetReportsQueryHandler(AdsAnalyticsServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<List<ReportListDto>> Handle(GetReportsQuery request, CancellationToken cancellationToken)
    {
        var reports = await _context.Reports
            .Where(r => r.AdvertiserId == request.AdvertiserId)
            .OrderByDescending(r => r.CreatedAt)
            .Skip(request.Skip)
            .Take(request.Take)
            .Select(r => new ReportListDto(
                r.Id,
                r.Name,
                r.ReportType.ToString(),
                r.StartDate,
                r.EndDate,
                r.Status.ToString(),
                r.CreatedAt))
            .ToListAsync(cancellationToken);

        return reports;
    }
}
