<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Story;
use App\Models\StoryComment;
use App\Services\SocialService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class StoryCommentController extends Controller
{
    public function __construct(private readonly SocialService $social) {}

    public function index(Request $request, int $storyId): JsonResponse
    {
        $story = Story::published()->findOrFail($storyId);

        return response()->json(
            $this->social->listStoryComments($story, $request->user()?->id, (int) $request->query('page', 1), 20)
        );
    }

    public function store(Request $request, int $storyId): JsonResponse
    {
        $story = Story::published()->findOrFail($storyId);

        $payload = $request->validate([
            'content' => ['required', 'string', 'min:1', 'max:10000'],
            'parent_id' => ['nullable', 'integer'],
        ]);

        $comment = $this->social->addStoryComment(
            $request->user(),
            $story,
            (string) $payload['content'],
            isset($payload['parent_id']) ? (int) $payload['parent_id'] : null,
        );

        return response()->json([
            'data' => $this->social->formatComment($comment, $request->user()->id, true),
        ], 201);
    }

    public function destroy(Request $request, int $storyId, int $commentId): JsonResponse
    {
        $comment = StoryComment::query()
            ->where('story_id', $storyId)
            ->findOrFail($commentId);

        $this->social->deleteStoryComment($request->user(), $comment);

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