<?php

declare(strict_types=1);

namespace Maestro\Core\Http\Controllers\Superadmin;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Models\MaestroModule;

class MaestroModuleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $modules = MaestroModule::query()
            ->orderBy('sort_order')
            ->orderBy('id')
            ->get()
            ->map(fn (MaestroModule $m) => [
                'slug' => $m->slug,
                'label' => $m->label,
                'is_enabled' => $m->is_enabled,
                'sort_order' => $m->sort_order,
            ]);

        return response()->json(['data' => $modules]);
    }

    public function update(Request $request, string $slug): JsonResponse
    {
        $module = MaestroModule::query()->where('slug', $slug)->firstOrFail();

        $validated = $request->validate([
            'is_enabled' => ['required', 'boolean'],
        ]);

        $module->update(['is_enabled' => $validated['is_enabled']]);

        return response()->json([
            'data' => [
                'slug' => $module->slug,
                'label' => $module->label,
                'is_enabled' => $module->is_enabled,
                'sort_order' => $module->sort_order,
            ],
        ]);
    }

    /**
     * Optional sort_order batch for module list UI.
     */
    public function reorder(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'order' => ['required', 'array', 'min:1'],
            'order.*' => ['string', Rule::exists('maestro_modules', 'slug')],
        ]);

        foreach ($validated['order'] as $index => $slug) {
            MaestroModule::query()->where('slug', $slug)->update(['sort_order' => $index]);
        }

        return $this->index($request);
    }
}
