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

namespace CMSMicroservice.Application.PublicMessageCQ.Commands.CreatePublicMessage;

public class CreatePublicMessageCommandHandler : IRequestHandler<CreatePublicMessageCommand, long>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;
    private readonly ILogger<CreatePublicMessageCommandHandler> _logger;

    public CreatePublicMessageCommandHandler(
        IApplicationDbContext context,
        ICurrentUserService currentUser,
        ILogger<CreatePublicMessageCommandHandler> logger)
    {
        _context = context;
        _currentUser = currentUser;
        _logger = logger;
    }

    public async Task<long> Handle(CreatePublicMessageCommand request, CancellationToken cancellationToken)
    {
        // 1. بررسی Admin
        var currentUserId = _currentUser.UserId;
        if (string.IsNullOrEmpty(currentUserId))
        {
            throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
        }

        if (!long.TryParse(currentUserId, out var createdByUserId))
        {
            throw new UnauthorizedAccessException("شناسه کاربر نامعتبر است");
        }

        // 2. ایجاد PublicMessage
        var message = new PublicMessage
        {
            Title = request.Title.Trim(),
            Content = request.Content.Trim(),
            Type = request.Type,
            Priority = request.Priority,
            IsActive = true,
            StartsAt = request.StartsAt,
            ExpiresAt = request.ExpiresAt,
            CreatedByUserId = createdByUserId,
            ViewCount = 0,
            LinkUrl = request.LinkUrl?.Trim(),
            LinkText = request.LinkText?.Trim()
        };

        _context.PublicMessages.Add(message);
        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation(
            "Public message created successfully. Id: {Id}, Title: {Title}, Type: {Type}, CreatedBy: {CreatedBy}",
            message.Id,
            message.Title,
            message.Type,
            createdByUserId
        );

        return message.Id;
    }
}
