<?php

namespace App\Http\Controllers\Dashboard;

use App\Enums\CatalogReviewStatus;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Event;
use App\Models\Role;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * Endpoint JSON para crear categorías “al vuelo” desde el formulario de evento (wizard).
 *
 * El estado de revisión depende del rol (staff vs organizador); ver {@see CatalogReviewStatus}.
 */
class CatalogCategoryController extends Controller
{
    /**
     * Alta rápida de categoría desde el formulario de evento (JSON).
     * Staff: aprobada al instante. Organizador: revisión pendiente.
     */
    public function store(Request $request): JsonResponse
    {
        $this->authorize('create', Event::class);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
        ]);

        $base = Str::slug($validated['name']) ?: 'categoria';
        $slug = $base;
        $n = 2;
        while (Category::query()->where('slug', $slug)->exists()) {
            $slug = $base.'-'.$n++;
        }

        $user = $request->user();
        $isStaff = $user && (
            $user->hasRole(Role::SLUG_SUPER_ADMIN) || $user->hasRole(Role::SLUG_ADMINISTRADOR)
        );

        $category = Category::query()->create([
            'name' => $validated['name'],
            'slug' => $slug,
            'description' => null,
            'parent_id' => null,
            'catalog_review_status' => $isStaff ? CatalogReviewStatus::Approved : CatalogReviewStatus::PendingReview,
            'catalog_submitted_by' => $isStaff ? null : $user?->id,
        ]);

        return response()->json([
            'category' => ['id' => $category->id, 'name' => $category->name],
            'requires_review' => ! $isStaff,
        ], 201);
    }
}
