<?php

namespace App\Http\Controllers\Forum;

use App\Http\Controllers\Controller;
use App\Models\Forum;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ForumController extends Controller
{
    /**
     * Display a listing of the forums.
     */
    public function index(): Response
    {
        $forums = Forum::query()
            ->where('is_active', true)
            ->orderBy('order')
            ->withCount('threads')
            ->with(['latestThreads.user'])
            ->get()
            ->map(function ($forum) {
                $latestThread = $forum->latestThreads->first();

                // Calculate posts count manually
                $postsCount = \App\Models\ForumPost::whereHas('thread', function ($query) use ($forum) {
                    $query->where('forum_id', $forum->id);
                })->count();

                return [
                    'id' => $forum->id,
                    'name' => $forum->name,
                    'slug' => $forum->slug,
                    'description' => $forum->description,
                    'threads_count' => $forum->threads_count,
                    'posts_count' => $postsCount,
                    'latest_thread' => $latestThread ? [
                        'title' => $latestThread->title,
                        'created_at' => $latestThread->created_at,
                        'user' => $latestThread->user,
                    ] : null,
                ];
            });

        return Inertia::render('forum/index', [
            'forums' => $forums,
        ]);
    }

    /**
     * Display the specified forum and its threads.
     */
    public function show(Request $request, Forum $forum): Response
    {
        if (! $forum->is_active) {
            abort(404);
        }

        $threads = $forum->threads()
            ->with('user')
            ->withCount('posts')
            ->orderByDesc('is_sticky')
            ->latest()
            ->paginate(15)
            ->withQueryString();

        // Manually load latest_post with user for each thread
        $threads->getCollection()->transform(function ($thread) {
            $latestPost = $thread->latestPost();

            return array_merge($thread->toArray(), [
                'latest_post' => $latestPost ? [
                    'created_at' => $latestPost->created_at,
                    'user' => $latestPost->user,
                ] : null,
            ]);
        });

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