<?php

declare(strict_types=1);

namespace Maestro\Core\Http\Controllers\Superadmin;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Models\MaestroModule;
use Maestro\Core\Services\InstallationHealthService;
use Maestro\Core\Support\ModuleDependencyMap;

class MaestroModuleController extends Controller
{
    public function index(): JsonResponse
    {
        $health = new InstallationHealthService();

        $modules = [];
        foreach (ModuleDependencyMap::allSlugs() as $slug) {
            $row = MaestroModule::query()->where('slug', $slug)->first();
            $modules[] = [
                'slug'         => $slug,
                'label'        => $row?->label ?? ucfirst($slug),
                'is_enabled'   => (bool) ($row?->is_enabled ?? false),
                'dependencies' => ModuleDependencyMap::dependenciesFor($slug),
                'dependents'   => ModuleDependencyMap::dependentsOf($slug),
                'health'       => $health->moduleReport($slug),
            ];
        }

        return response()->json([
            'checked_at'  => now()->toIso8601String(),
            'core_health' => $health->report(),
            'modules'     => $modules,
        ]);
    }

    public function activate(string $slug): JsonResponse
    {
        if (! in_array($slug, ModuleDependencyMap::allSlugs(), true)) {
            return response()->json(['message' => 'Unknown module.'], 404);
        }

        $row = MaestroModule::query()->where('slug', $slug)->first();

        if (! $row) {
            return response()->json([
                'message' => 'Module registry row not found. Run the seeders first.',
            ], 422);
        }

        if ($row->is_enabled) {
            return response()->json(['message' => 'Module is already active.'], 422);
        }

        $health = (new InstallationHealthService())->moduleReport($slug);

        $failing = array_filter(
            ['config', 'database'],
            fn (string $k): bool => $health[$k]['status'] === 'fail',
        );

        if ($failing !== []) {
            return response()->json([
                'message' => 'Cannot activate: '.implode(' and ', $failing).' checks are failing. Fix the listed commands first.',
                'health'  => $health,
            ], 422);
        }

        $row->update(['is_enabled' => true]);
        Cache::forget('maestro_module:'.$slug);

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