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

namespace BlogPlatform.Endpoints.Post;

public class GetPostRequest
{
    public int Id { get; set; }
}

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

    public override async Task HandleAsync(GetPostRequest 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;
        }
        
        List<GetCommentDto> comments = await db.Comments
            .Where(x => x.PostId == post.Id)
            .Include(comment => comment.User)
            .Select(x=> new GetCommentDto()
            {
                Id = x.Id,
                Content = x.Content,
                PostId = x.PostId,
                UserId = x.UserId,
                UserUsername = x.User.Username
            })
            .ToListAsync(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,
            Comments = comments,
        };

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