<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Support\Facades\File;
use Maestro\Core\Services\HostIntegrityService;
use Maestro\Core\Support\HostStubManifest;
use Tests\TestCase;

final class HostIntegrityCommandTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        $base = base_path();

        if (! File::isDirectory($base.'/database/seeders')) {
            File::makeDirectory($base.'/database/seeders', 0755, true);
        }

        File::put($base.'/composer.json', json_encode([
            'name' => 'test/app',
            'require' => ['maestro/core' => '^1.0'],
            'repositories' => [],
        ], JSON_THROW_ON_ERROR));

        File::put($base.'/package.json', json_encode([
            'private' => true,
            'dependencies' => [],
            'devDependencies' => [],
        ], JSON_THROW_ON_ERROR));

        $this->artisan('core:install')->assertSuccessful();

        $providerPath = app_path('Providers/AppServiceProvider.php');
        File::ensureDirectoryExists(dirname($providerPath));
        File::put($providerPath, <<<'PHP'
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->register(\App\Providers\CustomServiceProvider::class);
    }
}
PHP);
    }

    protected function tearDown(): void
    {
        $fork = base_path('resources/js/maestro/theme.js');
        if (File::exists($fork)) {
            File::delete($fork);
        }

        $link = base_path(HostStubManifest::LINK_STATE_FILE);
        if (File::exists($link)) {
            File::delete($link);
        }

        parent::tearDown();
    }

    public function test_host_integrity_passes_after_core_install(): void
    {
        $report = app(HostIntegrityService::class)->report();
        self::assertContains($report['overall'], ['ok', 'warn']);

        $this->artisan('maestro:host-integrity')->assertSuccessful();
    }

    public function test_host_integrity_fails_on_core_view_fork(): void
    {
        $fork = base_path('resources/js/maestro/theme.js');
        File::ensureDirectoryExists(dirname($fork));
        File::put($fork, '// fork');

        $this->artisan('maestro:host-integrity')->assertFailed();
    }

    public function test_host_integrity_detects_link_state_file(): void
    {
        File::put(base_path(HostStubManifest::LINK_STATE_FILE), '{"path":"/tmp"}');

        $this->artisan('maestro:host-integrity', ['--fail-on-warn' => true])->assertFailed();
    }

    public function test_host_integrity_json_output(): void
    {
        $this->artisan('maestro:host-integrity', ['--json' => true])->assertSuccessful();
    }
}
