<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Support\Facades\File;
use Tests\TestCase;

final class CoreInstallCommandTest 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));
    }

    public function test_custom_stubs_survive_force_and_managed_stubs_refresh(): void
    {
        $this->artisan('core:install')->assertSuccessful();

        $customBoot = base_path('resources/js/maestro/boot.js');
        self::assertFileExists($customBoot);

        File::put($customBoot, "// HOST CUSTOM MARKER\n".File::get($customBoot));

        $managedApp = base_path('resources/js/app.js');
        File::put($managedApp, '/** @maestro-core-managed */ OLD');

        $this->artisan('core:install', ['--force' => true])->assertSuccessful();

        self::assertStringContainsString('HOST CUSTOM MARKER', File::get($customBoot));
        self::assertStringContainsString('bootCore', File::get($managedApp));
        self::assertStringNotContainsString('OLD', File::get($managedApp));
    }

    public function test_core_config_not_republished_on_force_without_flag(): void
    {
        $this->artisan('vendor:publish', ['--tag' => 'core-config'])->assertSuccessful();

        $coreConfig = config_path('core.php');
        self::assertFileExists($coreConfig);

        File::put($coreConfig, "<?php\nreturn ['modules' => ['customers' => false]];\n");

        $this->artisan('core:install', ['--force' => true])->assertSuccessful();

        self::assertStringContainsString("'customers' => false", File::get($coreConfig));

        $this->artisan('core:install', ['--republish-config' => true])->assertSuccessful();

        self::assertStringNotContainsString("'customers' => false", File::get($coreConfig));
    }
}
