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 CreatePostEndpoint(BlogPlatformDbContext db) : Endpoint<CreatePostDto,GetPostDto>
{
    public override void Configure()
    {
        Post("/api/posts");
    }

    public override async Task HandleAsync(CreatePostDto req, CancellationToken ct)
    {
        Models.User checkingUser = await db.Users.FindAsync(req.UserId);

        if (checkingUser == null)
        {
            await Send.StringAsync("You must create a post with an existing user", 400);
            return;
        }

        Models.Post newPost = new()
        {
            Title = req.Title,
            Content = req.Content,
            Likes = req.Likes,
            UserId = req.UserId,
            User = checkingUser
        };
        
        db.Posts.Add(newPost);
        await db.SaveChangesAsync(ct);

        GetPostDto dto = new()
        {
            Id = newPost.Id,
            Title = req.Title,
            Content = req.Content,
            Likes = req.Likes,
            UserId = req.UserId,
            UserUsername = checkingUser.Username,
            UserEmail = checkingUser.Email,
        };
        
        await Send.OkAsync(dto, ct);

    }
}