using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.TagCQ.Commands.CreateTag;

public class CreateTagCommandHandler : IRequestHandler<CreateTagCommand, long>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<long> Handle(CreateTagCommand request, CancellationToken cancellationToken)
    {
        // بررسی تکراری نبودن نام
        var existingTag = await _context.Tags
            .FirstOrDefaultAsync(t => t.Name == request.Name, cancellationToken);

        if (existingTag != null)
        {
            throw new BadRequestException($"تگ با نام '{request.Name}' قبلاً ثبت شده است");
        }

        var tag = new Tag
        {
            Name = request.Name,
            Title = request.Title,
            Description = request.Description,
            SortOrder = request.SortOrder,
            IsActive = request.IsActive
        };

        _context.Tags.Add(tag);
        await _context.SaveChangesAsync(cancellationToken);

        return tag.Id;
    }
}
