<?php

namespace App\Http\Controllers\Admin;

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

class ForumManagementController extends Controller
{
    /**
     * Display a listing of all forums (for admin management).
     */
    public function index(): Response
    {
        $forums = Forum::query()
            ->withCount('threads')
            ->orderBy('order')
            ->get()
            ->map(function ($forum) {
                $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,
                    'order' => $forum->order,
                    'is_active' => $forum->is_active,
                    'threads_count' => $forum->threads_count,
                    'posts_count' => $postsCount,
                    'created_at' => $forum->created_at,
                ];
            });

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

    /**
     * Store a newly created forum.
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['required', 'string', 'max:255', 'unique:forums,slug'],
            'description' => ['required', 'string', 'max:1000'],
            'order' => ['required', 'integer', 'min:0'],
            'is_active' => ['boolean'],
        ]);

        Forum::create($validated);

        return redirect()->route('admin.forums.index')
            ->with('success', 'Foro creado exitosamente.');
    }

    /**
     * Update the specified forum.
     */
    public function update(Request $request, Forum $forum): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['required', 'string', 'max:255', 'unique:forums,slug,'.$forum->id],
            'description' => ['required', 'string', 'max:1000'],
            'order' => ['required', 'integer', 'min:0'],
            'is_active' => ['boolean'],
        ]);

        $forum->update($validated);

        return redirect()->route('admin.forums.index')
            ->with('success', 'Foro actualizado exitosamente.');
    }

    /**
     * Remove the specified forum.
     */
    public function destroy(Forum $forum): RedirectResponse
    {
        // Check if forum has threads
        if ($forum->threads()->count() > 0) {
            return redirect()->route('admin.forums.index')
                ->with('error', 'No se puede eliminar un foro con hilos activos.');
        }

        $forum->delete();

        return redirect()->route('admin.forums.index')
            ->with('success', 'Foro eliminado exitosamente.');
    }

    /**
     * Display threads of a specific forum for moderation.
     */
    public function threads(Forum $forum): Response
    {
        $threads = $forum->threads()
            ->with('user')
            ->withCount('posts')
            ->orderByDesc('is_sticky')
            ->latest()
            ->paginate(20)
            ->withQueryString();

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

    /**
     * Toggle sticky status of a thread.
     */
    public function toggleSticky(Request $request, int $threadId): RedirectResponse
    {
        $thread = \App\Models\ForumThread::findOrFail($threadId);
        $thread->update(['is_sticky' => ! $thread->is_sticky]);

        return back()->with('success', $thread->is_sticky ? 'Hilo fijado.' : 'Hilo desfijado.');
    }

    /**
     * Toggle locked status of a thread.
     */
    public function toggleLock(Request $request, int $threadId): RedirectResponse
    {
        $thread = \App\Models\ForumThread::findOrFail($threadId);
        $thread->update(['is_locked' => ! $thread->is_locked]);

        return back()->with('success', $thread->is_locked ? 'Hilo bloqueado.' : 'Hilo desbloqueado.');
    }
}
