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

namespace BlogPlatform.Endpoints.Comment;

public class UpdateCommentEndpoint(BlogPlatformDbContext db) : Endpoint<UpdateCommentDto,GetCommentDto>
{
    public override void Configure()
    {
        Put("/api/comments/{@id}", x=> new{id=x.Id});
    }

    public override async Task HandleAsync(UpdateCommentDto req, CancellationToken ct)
    {
        Models.Comment? comment = await db.Comments.FindAsync(req.Id);
        // Checking if the user and post IDs exist in our database
        Models.User? checkingUser = await db.Users.FindAsync(req.UserId);
        Models.Post? checkingPost = await db.Posts.FindAsync(req.PostId);

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

        await db.SaveChangesAsync(ct);


        // Returning the response with DTO
        GetCommentDto dto = new()
        {
            Id = comment.Id,
            Content = comment.Content,
            PostId = comment.PostId,
            PostTitle = checkingPost.Title,
            UserId = comment.UserId,
            UserUsername = checkingUser.Username

        };

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