<?php

namespace App\Http\Controllers\Forum;

use App\Http\Controllers\Controller;
use App\Models\ForumPost;
use App\Models\ForumThread;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Gate;

class ForumModerationController extends Controller
{
    /**
     * Delete a thread.
     */
    public function deleteThread(ForumThread $thread): RedirectResponse
    {
        // Allow if user can moderate forum OR if user is the author
        if (! Gate::check('forum.delete') && $thread->user_id !== auth()->id()) {
            return back()->withErrors(['error' => 'No tienes permiso para eliminar este hilo.']);
        }

        $forumSlug = $thread->forum->slug;
        $thread->delete();

        return redirect()->route('forum.show', $forumSlug)
            ->with('success', 'Hilo eliminado exitosamente.');
    }

    /**
     * Delete a post.
     */
    public function deletePost(ForumPost $post): RedirectResponse
    {
        // Allow if user can moderate forum OR if user is the author
        if (! Gate::check('forum.delete') && $post->user_id !== auth()->id()) {
            return back()->withErrors(['error' => 'No tienes permiso para eliminar este comentario.']);
        }

        $post->delete();

        return back()->with('success', 'Comentario eliminado.');
    }

    /**
     * Toggle sticky status (Curators/Admins only).
     */
    public function toggleSticky(ForumThread $thread): RedirectResponse
    {
        if (! Gate::check('forum.moderate')) {
            return back()->withErrors(['error' => 'No tienes permisos de moderación.']);
        }

        $thread->update(['is_sticky' => ! $thread->is_sticky]);

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

    /**
     * Toggle locked status (Curators/Admins only).
     */
    public function toggleLock(ForumThread $thread): RedirectResponse
    {
        if (! Gate::check('forum.moderate')) {
            return back()->withErrors(['error' => 'No tienes permisos de moderación.']);
        }

        $thread->update(['is_locked' => ! $thread->is_locked]);

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