<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreReplyRequest;
use App\Http\Resources\ReplyResource;
use App\Models\Comment;
use App\Models\Reply;
use App\Services\ReplyService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Gate;

class ReplyController extends Controller
{
    public function __construct(private ReplyService $replyService) {}

    public function index(Comment $comment): AnonymousResourceCollection
    {
        $replies = $this->replyService->forComment($comment);
        return ReplyResource::collection($replies);
    }

    public function store(StoreReplyRequest $request, Comment $comment): JsonResponse
    {
        $reply = $this->replyService->create(
            $request->user(),
            $comment,
            $request->validated('content')
        );
        $reply->load(['user', 'likes.user']);
        $reply->loadCount('likes');

        return response()->json([
            'message' => 'Reply added.',
            'reply'   => new ReplyResource($reply),
        ], 201);
    }

    public function update(StoreReplyRequest $request, Reply $reply): JsonResponse
    {
        Gate::authorize('update', $reply);

        $updated = $this->replyService->update($reply, $request->validated('content'));
        $updated->load(['user', 'likes.user']);
        $updated->loadCount('likes');

        return response()->json([
            'message' => 'Reply updated.',
            'reply'   => new ReplyResource($updated),
        ]);
    }

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