namespace CMSMicroservice.Application.AppVersionCQ.Queries.GetAllAppVersions;

/// <summary>
/// Handler برای دریافت همه نسخه‌های اپلیکیشن‌ها
/// </summary>
public class GetAllAppVersionsQueryHandler : IRequestHandler<GetAllAppVersionsQuery, List<AppVersionItemDto>>
{
    private readonly IApplicationDbContext _context;

    public GetAllAppVersionsQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<List<AppVersionItemDto>> Handle(GetAllAppVersionsQuery request, CancellationToken cancellationToken)
    {
        var query = _context.AppVersions
            .Where(v => !v.IsDeleted);

        if (!request.IncludeInactive)
        {
            query = query.Where(v => v.IsActive);
        }

        var versions = await query
            .OrderBy(v => v.AppName)
            .Select(v => new AppVersionItemDto
            {
                Id = v.Id,
                AppName = v.AppName,
                CurrentVersion = v.CurrentVersion,
                MinRequiredVersion = v.MinRequiredVersion,
                RequiresFullCacheClear = v.RequiresFullCacheClear,
                UpdateMessage = v.UpdateMessage,
                ReleaseNotes = v.ReleaseNotes,
                IsActive = v.IsActive,
                Created = v.Created,
                LastModified = v.LastModified
            })
            .ToListAsync(cancellationToken);

        return versions;
    }
}
