<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\Post;
use App\Services\SpamDetector;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    // GET /api/v1/posts/{slug}/comments
    public function index(string $slug)
    {
        $post = Post::where('slug', $slug)->firstOrFail();

        $comments = Comment::approved()
            ->where('post_id', $post->id)
            ->whereNull('parent_id')
            ->with(['replies' => fn($q) => $q->approved()->oldest()])
            ->latest()
            ->get()
            ->map(fn($c) => [
                'id'          => $c->id,
                'author_name' => $c->author_name,
                'content'     => $c->content,
                'created_at'  => $c->created_at,
                'replies'     => $c->replies->map(fn($r) => [
                    'id'          => $r->id,
                    'author_name' => $r->author_name,
                    'content'     => $r->content,
                    'created_at'  => $r->created_at,
                ]),
            ]);

        return response()->json([
            'data'  => $comments,
            'total' => $comments->count(),
        ]);
    }

    // POST /api/v1/posts/{slug}/comments
    public function store(Request $request, string $slug)
    {
        $post = Post::where('slug', $slug)->firstOrFail();

        $data = $request->validate([
            'name'    => 'required|string|max:100',
            'comment' => 'required|string|min:8|max:2000',
        ]);

        // Rate limit: max 3 comments per IP per hour
        $recentCount = Comment::where('author_ip', $request->ip())
            ->where('created_at', '>=', now()->subHour())
            ->count();

        if ($recentCount >= 3) {
            return response()->json(['message' => 'Too many comments. Please wait before posting again.'], 429);
        }

        // Spam / relevance analysis
        $check = SpamDetector::analyze($post, $data['comment']);

        if ($check['status'] === 'spam') {
            return response()->json(['message' => 'Your comment was flagged as spam and not published.'], 422);
        }

        $comment = Comment::create([
            'post_id'     => $post->id,
            'author_name' => htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'),
            'author_ip'   => $request->ip(),
            'content'     => htmlspecialchars($data['comment'], ENT_QUOTES, 'UTF-8'),
            'status'      => $check['status'],
        ]);

        if ($check['status'] === 'approved') {
            $post->increment('comments_count');
        }

        return response()->json([
            'message' => $check['status'] === 'approved'
                ? 'Comment posted!'
                : 'Comment submitted! It will appear after review.',
            'status'  => $check['status'],
            'comment' => $check['status'] === 'approved' ? [
                'id'          => $comment->id,
                'author_name' => $comment->author_name,
                'content'     => $comment->content,
                'created_at'  => $comment->created_at,
                'replies'     => [],
            ] : null,
        ], 201);
    }
}
