<?php

declare(strict_types=1);

namespace Tests\Feature;

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

final class MakeCustomFeatureCommandTest 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'],
        ], JSON_THROW_ON_ERROR));

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

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

    public function test_scaffolds_custom_feature_and_patches_orchestrators(): void
    {
        $this->artisan('make:custom-feature', [
            'name' => 'Reservations',
            '--slug' => 'test_reservations',
            '--api-prefix' => 'reservations',
            '--label' => 'Test Reservations',
        ])->assertSuccessful();

        self::assertFileExists(app_path('Custom/Features/Reservations/Providers/ReservationsServiceProvider.php'));
        self::assertFileExists(app_path('Custom/Features/Reservations/Database/Seeders/ReservationsSeeder.php'));
        self::assertFileExists(base_path('routes/custom/reservations.php'));
        self::assertFileExists(base_path('resources/js/modules/custom/reservations/routes.js'));
        self::assertFileExists(base_path('resources/js/modules/custom/reservations/views/Index.vue'));

        $provider = File::get(app_path('Providers/CustomServiceProvider.php'));
        self::assertStringContainsString('ReservationsServiceProvider::class', $provider);

        $routes = File::get(base_path('resources/js/modules/custom/routes.js'));
        self::assertStringContainsString('reservationsRoutes', $routes);
        self::assertStringContainsString('./reservations/routes.js', $routes);

        $seeder = File::get(base_path('database/seeders/CustomDatabaseSeeder.php'));
        self::assertStringContainsString('ReservationsSeeder::class', $seeder);

        $featureRoutes = File::get(base_path('resources/js/modules/custom/reservations/routes.js'));
        self::assertStringContainsString('test_reservations', $featureRoutes);
        self::assertStringContainsString('custom/reservations', $featureRoutes);
    }

    public function test_skips_existing_files_on_second_run(): void
    {
        $this->artisan('make:custom-feature', ['name' => 'Billing'])->assertSuccessful();

        $path = app_path('Custom/Features/Billing/Providers/BillingServiceProvider.php');
        File::put($path, '// kept');

        $this->artisan('make:custom-feature', ['name' => 'Billing'])->assertSuccessful();

        self::assertSame('// kept', File::get($path));
    }
}
