<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCommentRequest;
use App\Http\Resources\CommentResource;
use App\Models\Comment;
use App\Models\Post;
use App\Services\CommentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Gate;

class CommentController extends Controller
{
    public function __construct(private CommentService $commentService) {}

    public function index(Post $post): AnonymousResourceCollection
    {
        $comments = $this->commentService->forPost($post);
        return CommentResource::collection($comments);
    }

    public function store(StoreCommentRequest $request, Post $post): JsonResponse
    {
        $comment = $this->commentService->create(
            $request->user(),
            $post,
            $request->validated('content')
        );
        $comment->load(['user', 'likes.user', 'replies.user', 'replies.likes']);
        $comment->replies->each->loadCount('likes');
        $comment->loadCount('likes');

        return response()->json([
            'message' => 'Comment added.',
            'comment' => new CommentResource($comment),
        ], 201);
    }

    public function update(StoreCommentRequest $request, Comment $comment): JsonResponse
    {
        Gate::authorize('update', $comment);

        $updated = $this->commentService->update($comment, $request->validated('content'));
        $updated->load(['user', 'likes.user', 'replies.user', 'replies.likes']);
        $updated->replies->each->loadCount('likes');
        $updated->loadCount('likes');

        return response()->json([
            'message' => 'Comment updated.',
            'comment' => new CommentResource($updated),
        ]);
    }

    public function destroy(Request $request, Comment $comment): JsonResponse
    {
        Gate::authorize('delete', $comment);
        $this->commentService->delete($comment);
        return response()->json(['message' => 'Comment deleted.']);
    }
}
