<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use App\Models\Registration;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    public function index(Request $request)
    {
        $request->validate(['registration_id' => 'required|exists:registrations,id']);

        $comments = Comment::where('registration_id', $request->registration_id)
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(fn($c) => [
                'comment'          => $c->comment,
                'author'           => auth()->user()->name,
                'created_at_human' => $c->created_at->diffForHumans(),
            ])
            ->values(); // ← add this

        return response()->json(['comments' => $comments]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'registration_id' => 'required|exists:registrations,id',
            'comment'         => 'required|string|max:1000',
        ]);

        Registration::findOrFail($request->registration_id);

        $comment = Comment::create([
            'registration_id' => $request->registration_id,
            'comment'         => $request->comment,
        ]);

        return response()->json([
            'comment' => [
                'comment'          => $comment->comment,
                'author'           => auth()->user()->name,
                'created_at_human' => $comment->created_at->diffForHumans(),
            ]
        ]);
    }
}