<?php

namespace App\Http\Controllers\Forum;

use App\Http\Controllers\Controller;
use App\Http\Requests\Forum\StoreThreadRequest;
use App\Models\Forum;
use App\Models\ForumThread;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class ThreadController extends Controller
{
    /**
     * Display the specified thread.
     */
    public function show(Forum $forum, ForumThread $thread): Response
    {
        // Verificar que el hilo pertenece al foro
        if ($thread->forum_id !== $forum->id) {
            abort(404);
        }

        // Incrementar vistas
        $thread->incrementViews();

        // Eager load everything needed for the view
        $thread->load('user');

        $posts = $thread->posts()
            ->with(['user', 'replies.user', 'replies.votes', 'votes'])
            ->whereNull('parent_id') // Solo posts principales (no respuestas anidadas)
            ->oldest() // Orden cronológico
            ->paginate(20);

        // Transform posts to check for user votes
        $posts->getCollection()->transform(function ($post) {
            if (auth()->check()) {
                $post->user_vote = $post->userVote(auth()->id());
            }

            return $post;
        });

        return Inertia::render('forum/thread/show', [
            'forum' => $forum,
            'thread' => $thread,
            'posts' => $posts,
        ]);
    }

    /**
     * Store a newly created thread in storage.
     */
    public function store(StoreThreadRequest $request, Forum $forum): RedirectResponse
    {
        $thread = $forum->threads()->create([
            'user_id' => auth()->id(),
            'title' => $request->title,
            'content' => $request->content,
        ]);

        return redirect()->route('forum.thread.show', [
            'forum' => $forum->slug,
            'thread' => $thread->slug,
        ])->with('success', 'Hilo creado exitosamente.');
    }
}
