using BlogPlatform.DTO.Post.Request;
using BlogPlatform.DTO.Post.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;

namespace BlogPlatform.Endpoints.Post;

public class UpdatePostUnLikeEndpoint(BlogPlatformDbContext db) : Endpoint<PatchLikePostDto,GetPostDto>
{
    public override void Configure()
    {
        Patch("/api/posts/{@id}/unlike", x => new{x.Id});
    }

    public override async Task HandleAsync(PatchLikePostDto req, CancellationToken ct)
    {
        Models.Post post = await db.Posts
            .Include(post => post.User)
            .SingleOrDefaultAsync(x => x.Id == req.Id);

        if (post == null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        
        post.Likes--;
        
        await db.SaveChangesAsync(ct);

        
        GetPostDto dto = new()
        {
            Id = post.Id,
            Title = post.Title,
            Content = post.Content,
            Likes = post.Likes,
            UserId = post.UserId,
            UserUsername = post.User.Username,
            UserEmail = post.User.Email,
        };

        await Send.OkAsync(dto, ct);
    }
}