using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.PublicMessageCQ.Queries.GetActiveMessages;

public class GetActiveMessagesQueryHandler : IRequestHandler<GetActiveMessagesQuery, List<PublicMessageDto>>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<GetActiveMessagesQueryHandler> _logger;

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

    public async Task<List<PublicMessageDto>> Handle(GetActiveMessagesQuery request, CancellationToken cancellationToken)
    {
        var now = DateTime.Now;

        var query = _context.PublicMessages
            .Where(x => !x.IsDeleted 
                && x.IsActive 
                && x.StartsAt <= now 
                && x.ExpiresAt >= now);

        // فیلتر اختیاری اولویت
        if (request.MinPriority.HasValue)
        {
            query = query.Where(x => (int)x.Priority >= request.MinPriority.Value);
        }

        var messages = await query
            .OrderByDescending(x => x.Priority)
            .ThenByDescending(x => x.Created)
            .Select(x => new PublicMessageDto
            {
                Id = x.Id,
                Title = x.Title,
                Content = x.Content,
                Type = x.Type,
                TypeName = GetTypeName(x.Type),
                Priority = x.Priority,
                PriorityName = GetPriorityName(x.Priority),
                StartsAt = x.StartsAt,
                ExpiresAt = x.ExpiresAt,
                LinkUrl = x.LinkUrl,
                LinkText = x.LinkText,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

        _logger.LogInformation(
            "Retrieved {Count} active messages",
            messages.Count
        );

        return messages;
    }

    private static string GetTypeName(MessageType type)
    {
        return type switch
        {
            MessageType.Announcement => "اطلاعیه",
            MessageType.News => "اخبار",
            MessageType.Warning => "هشدار",
            MessageType.Promotion => "تبلیغات",
            MessageType.SystemUpdate => "به‌روزرسانی سیستم",
            MessageType.Event => "رویداد",
            _ => "نامشخص"
        };
    }

    private static string GetPriorityName(MessagePriority priority)
    {
        return priority switch
        {
            MessagePriority.Low => "کم",
            MessagePriority.Medium => "متوسط",
            MessagePriority.High => "بالا",
            MessagePriority.Urgent => "فوری",
            _ => "نامشخص"
        };
    }
}
