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

namespace BlogPlatform.Endpoints.Comment;

public class CreateCommentEndpoint(BlogPlatformDbContext db) : Endpoint<CreateCommentDto,GetCommentDto>
{
    public override void Configure()
    {
        Post("/api/comments");
    }

    public override async Task HandleAsync(CreateCommentDto req, CancellationToken ct)
    {
        // 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)
        {
            await Send.StringAsync("You must add a comment on a Post that exist and of a User that exists", 400);
            return;
        }

        // User and Post exists adding the comment
        Models.Comment newComment = new()
        {
            Content = req.Content,
            PostId = req.PostId,
            Post = checkingPost,
            UserId = req.UserId,
            User = checkingUser,

        };

        db.Comments.Add(newComment);
        await db.SaveChangesAsync(ct);


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

        };

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