<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CommentResource;
use App\Models\Comment;
use App\Models\Video;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    public function index(Video $video)
    {
        $comments = $video->comments()
            ->with('user:id,name,avatar,is_admin')
            ->latest()
            ->paginate(15);

        return CommentResource::collection($comments);
    }

    public function store(Request $request, Video $video)
    {
        $data = $request->validate([
            'body' => ['required', 'string', 'max:2000'],
        ]);

        $comment = $video->comments()->create([
            'user_id' => $request->user()->id,
            'body' => $data['body'],
        ]);

        $comment->load('user:id,name,avatar,is_admin');

        return new CommentResource($comment);
    }

    public function destroy(Request $request, Comment $comment)
    {
        $user = $request->user();

        // Owner or admin may delete.
        abort_unless($comment->user_id === $user->id || $user->is_admin, 403);

        $comment->delete();

        return response()->json(['message' => 'Deleted.']);
    }
}
