<?php

namespace App\Http\Controllers\CustomArticle;

use App\Http\Controllers\Core\Auth;
use App\Http\Resources\CustomArticle\CommentCollection;
use App\Http\Resources\CustomArticle\CommentResource;
use App\Models\CustomArticle\Article;
use App\Models\CustomArticle\Comment;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CommentController extends Controller
{

    /**
     * 评论列表
     * @param  Request  $request
     * @param  Article  $article
     * @return CommentCollection
     */
    public function index(Request $request, Article $article)
    {
        $comments = $article->comments()->paginate($request->get('per_page', 20));
        foreach ($comments as $comment) {
            $comment->user;
            $comment->reply;
        }
        return new CommentCollection($comments);
    }


    /**
     * 评论详情
     * @param  Article  $article
     * @param  Comment  $comment
     * @return CommentResource
     */
    public function show(Article $article, Comment $comment)
    {
        $comment->user;
        $comment->reply;
        return new CommentResource($comment);
    }


    public function store(Request $request, Article $article, Comment $comment)
    {
        $this->validate($request, [
            'content' => 'required|max:2',
        ]);

        $comment->article()->associate($article);
        $comment->uid = Auth::auth();
        $comment->save();
        return new CommentResource($comment);
    }

    /**
     * 删除评论
     * @param  Article  $article
     * @param  Comment  $comment
     * @return CommentResource
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function destroy(Article $article, Comment $comment)
    {
        $this->authorize('delete', $comment);

        $comment->delete();

        return new CommentResource($comment);
    }
}
