using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Domain.Entities.Forum.Logs;
using SharedKernel.Results;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Forum.PostLink.Click;

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result<Response>>
{
    public async Task<Result<Response>> Handle(Command request, CancellationToken ct)
    {
        var link = await db.PostLink.FirstOrDefaultAsync(x => x.ID == request.PostLinkID && !x.IsDisabled, ct);
        if (link is null)
        {
            return Result.Failure<Response>(Error.NotFound("PostLink.NotFound", "링크를 찾을 수 없습니다."));
        }

        link.Clicks++;

        var log = new PostLinkClickLog
        {
            PostID = link.PostID,
            PostLinkID = link.ID,
            MemberID = request.MemberID,
            IpAddress = request.IpAddress,
            UserAgent = request.UserAgent
        };

        await db.PostLinkClickLog.AddAsync(log, ct);
        await db.SaveChangesAsync(ct);

        return new Response(link.Url);
    }
}