using CMSMicroservice.Domain.Entities.Configuration;

namespace CMSMicroservice.Application.AppVersionCQ.Commands.UpdateAppVersion;

/// <summary>
/// Handler برای آپدیت یا ایجاد نسخه جدید اپلیکیشن
/// </summary>
public class UpdateAppVersionCommandHandler : IRequestHandler<UpdateAppVersionCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<UpdateAppVersionCommandHandler> _logger;

    public UpdateAppVersionCommandHandler(
        IApplicationDbContext context,
        ILogger<UpdateAppVersionCommandHandler> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<Unit> Handle(UpdateAppVersionCommand request, CancellationToken cancellationToken)
    {
        // پیدا کردن نسخه موجود برای این اپ
        var existingVersion = await _context.AppVersions
            .Where(v => v.AppName == request.AppName && !v.IsDeleted)
            .FirstOrDefaultAsync(cancellationToken);

        if (existingVersion != null)
        {
            // آپدیت نسخه موجود
            existingVersion.CurrentVersion = request.CurrentVersion;
            existingVersion.MinRequiredVersion = request.MinRequiredVersion ?? request.CurrentVersion;
            existingVersion.RequiresFullCacheClear = request.RequiresFullCacheClear;
            existingVersion.UpdateMessage = request.UpdateMessage;
            existingVersion.ReleaseNotes = request.ReleaseNotes;

            _logger.LogInformation(
                "App version updated: {AppName} v{Version}, CacheClear={CacheClear}, Reason={Reason}",
                request.AppName, request.CurrentVersion, request.RequiresFullCacheClear, request.UpdateReason);
        }
        else
        {
            // ایجاد نسخه جدید
            var newVersion = new AppVersion
            {
                AppName = request.AppName,
                CurrentVersion = request.CurrentVersion,
                MinRequiredVersion = request.MinRequiredVersion ?? request.CurrentVersion,
                RequiresFullCacheClear = request.RequiresFullCacheClear,
                UpdateMessage = request.UpdateMessage,
                ReleaseNotes = request.ReleaseNotes,
                IsActive = true
            };

            _context.AppVersions.Add(newVersion);

            _logger.LogInformation(
                "New app version created: {AppName} v{Version}, CacheClear={CacheClear}, Reason={Reason}",
                request.AppName, request.CurrentVersion, request.RequiresFullCacheClear, request.UpdateReason);
        }

        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
