<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Maestro\Core\Database\Seeders\ModuleAndNavigationSeeder;
use Maestro\Core\Database\Seeders\UserSeeder;
use Maestro\Core\Support\PermissionGuardName;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;
use Tests\Fixtures\AuthTestUser;
use Tests\TestCase;

class InstallationHealthApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_installation_health_forbidden_without_superadmin(): void
    {
        $this->seed([UserSeeder::class, ModuleAndNavigationSeeder::class]);

        $user = AuthTestUser::query()->where('email', 'demo@example.com')->first();
        self::assertNotNull($user);

        $guardName = PermissionGuardName::forApp();
        $role = Role::findByName('admin', $guardName);
        self::assertNotNull($role);
        $role->revokePermissionTo('platform.superadmin');
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $response = $this->actingAs($user, 'web')->getJson('/api/superadmin/installation-health');

        $response->assertForbidden();
    }

    public function test_installation_health_returns_grouped_checks_when_seeded(): void
    {
        $this->seed([UserSeeder::class, ModuleAndNavigationSeeder::class]);

        $user = AuthTestUser::query()->where('email', 'demo@example.com')->first();
        self::assertNotNull($user);

        $response = $this->actingAs($user, 'web')->getJson('/api/superadmin/installation-health');

        $response->assertOk();
        $response->assertJsonStructure([
            'data' => [
                'checked_at',
                'overall',
                'groups' => [
                    '*' => ['id', 'title', 'steps'],
                ],
            ],
        ]);

        $groups = $response->json('data.groups');
        self::assertIsArray($groups);
        self::assertCount(4, $groups);
        self::assertSame('core', $groups[0]['id']);

        foreach ($groups as $group) {
            self::assertIsArray($group['steps']);
            self::assertNotEmpty($group['steps']);
            foreach ($group['steps'] as $step) {
                self::assertArrayHasKey('id', $step);
                self::assertArrayHasKey('status', $step);
                self::assertContains($step['status'], ['ok', 'warn', 'fail']);
            }
        }
    }

    /**
     * Unseeded installs may still migrate CORE tables — health should resolve without crashing.
     */
    public function test_installation_health_succeeds_after_migrations_without_module_seed(): void
    {
        $this->seed([UserSeeder::class]);

        $user = AuthTestUser::query()->where('email', 'demo@example.com')->first();
        self::assertNotNull($user);

        $response = $this->actingAs($user, 'web')->getJson('/api/superadmin/installation-health');

        $response->assertOk();
        $overall = $response->json('data.overall');
        self::assertContains($overall, ['ok', 'warn', 'fail']);
    }
}
