using Microsoft.EntityFrameworkCore; using T120B165_ImgBoard.Data; using T120B165_ImgBoard.Models; using T120B165_ImgBoard.Utils; namespace T120B165_ImgBoard.Services; public interface ICommentService { Task Create(string text, User author, Post post); Task GetById(int commentId); Task> GetAll(int pageNumber = 1); Task Delete(Comment comment); Task Update(Comment comment); } public class CommentService(ImgBoardContext context): ICommentService { private const int PageSize = 20; public async Task Create(string text, User author, Post post) { var entry = new Comment { Text = text, Author = author, OriginalPost = post, Created = DateTime.Now, }; await context.Comments.AddAsync(entry); await context.SaveChangesAsync(); return entry; } public async Task GetById(int commentId) { return await context.Comments.Where(t => t.Id == commentId) .Include(b => b.Author) .Include(b => b.OriginalPost) .FirstOrDefaultAsync(); } public async Task> GetAll(int pageNumber = 1) { var totalCount = await context.Comments.CountAsync(); var items = await context.Comments .Skip((pageNumber - 1) * PageSize) .Take(PageSize) .Include(b => b.Author) .Include(b => b.OriginalPost) .ToListAsync(); return new PagedList(items, pageNumber, PageSize, totalCount); } public async Task Delete(Comment comment) { context.Comments.Remove(comment); await context.SaveChangesAsync(); return true; } public async Task Update(Comment comment) { context.Comments.Update(comment); await context.SaveChangesAsync(); return comment; } }