using BlogPlatform.DTO.Comment.Request;
using BlogPlatform.DTO.Comment.Response;
using BlogPlatform.DTO.Post.Request;
using BlogPlatform.DTO.Post.Response;
using FastEndpoints;

namespace BlogPlatform.Endpoints.Post;

public class UpdatePostEndpoint(BlogPlatformDbContext db) : Endpoint<UpdatePostDto,GetPostDto>
{
    public override void Configure()
    {
        Put("/api/post/{@id}", x=> new{id=x.Id});
    }

    public override async Task HandleAsync(UpdatePostDto req, CancellationToken ct)
    {
        Models.Post post = await db.Posts.FindAsync(req.Id);
        Models.User checkingUser = await db.Users.FindAsync(req.UserId);

        if (checkingUser == null || post == null)
        {
            await Send.StringAsync("You must add a comment on a Post that exist and of a User that exists", 400);
            return;
        }
        
        post.Content = req.Content;
        post.Title = req.Title;
        post.UserId = checkingUser.Id;
        
        await db.SaveChangesAsync(ct);


        // Returning the response with DTO
        GetPostDto dto = new()
        {
            Id = post.Id,
            Title = req.Title,
            Content = req.Content,
            Likes = post.Likes,
            UserId = req.UserId,
            UserUsername = checkingUser.Username,
            UserEmail = checkingUser.Email,
        };
        
        await Send.OkAsync(dto, ct);
    }
}