<?php

namespace Artemis\Faq\Http\Controllers\api\v1;

use Illuminate\Http\Request;
use Artemis\Faq\Models\Comment;
use Illuminate\Http\JsonResponse;
use Artemis\Faq\Traits\Commentable;
use Illuminate\Database\Eloquent\Model;
use Artemis\Faq\Http\Requests\CommentStoreRequest;
use Artemis\Faq\Http\Controllers\api\ApiController;
use Artemis\Faq\Http\Resources\CommentResource;
use Artemis\Faq\Http\Requests\CommentUpdateRequest;
use Symfony\Component\HttpFoundation\Response as ResponseCode;

class CommentController extends ApiController
{
    public function index(Request $request): JsonResponse
    {
        $perPage = $this->getPerPage($request);
        $page = $this->getPage($request);
        
        $comments = Comment::paginate(perPage: $perPage, page: $page);
        $data = [
                'data' => CommentResource::collection($comments),
            ] + $this->paginateResult($comments);
        
        return $this->success($data);
    }
    
    public function store(CommentStoreRequest $request): JsonResponse
    {
        /**
         * @var Model|Commentable $commentableModel
         */
        $commentableModel = resolveModelClass($request->commentable_type, $request->commentable_id);
        
        $commentableModel->addComment($request->body, $request->user()->id);
        
        return $this->success(status: ResponseCode::HTTP_CREATED);
    }
    
    public function show(Comment $comment): JsonResponse
    {
        return $this->success(new CommentResource($comment));
    }
    
    public function update(CommentUpdateRequest $request, Comment $comment): JsonResponse
    {
        $comment->update($request->validated());
        
        return $this->success();
    }
    
    public function destroy(Comment $comment): JsonResponse
    {
        $comment->delete();
        
        return $this->success();
    }
}
