<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;

class MakeCrudsCommand extends Command
{
  /**
   * The name and signature of the console command.
   *
   * @var string
   */
  protected $signature = 'make:cruds {--rollback}';

  /**
   * The console command description.
   *
   * @var string
   */
  protected $description = 'Generate or rollback multiple CRUD files based on the list in CrudGenerator.php';

  /**
   * Execute the console command.
   *
   * @return int
   */
  public function handle()
  {
    $process = new Process(['git', 'status', '--porcelain']);
    $process->run();
    echo $process->getOutput();

    if ($process->isSuccessful() && !empty(trim($process->getOutput()))) {
      $this->error("Eksekusi tidak dapat dilakukan: Ada file yang belum di-commit. Mohon commit atau stash perubahan Anda terlebih dahulu.");
      return 0;
    }

    $migrations = config('crudgenerator.data');
    $isRollback = $this->option('rollback');

    if (empty($migrations)) {
      $this->error("Tidak ada migrasi yang ditemukan di CrudGenerator.php.");
      return 1;
    }

    $action = $isRollback ? 'rollback' : 'generation';
    $this->info("Memulai multi-CRUD {$action}...");

    foreach ($migrations as $data) {
      $this->info("Memproses: {$data['migration']}");

      $options = [
        'migration_file' => $data['migration'],
      ];

      if ($isRollback) {
        $options['--rollback'] = true;
      }

      // We don't need to pass label, icon, etc. as MakeCrudCommand now reads them from config
      // based on the migration file match.

      $options['--format'] = true; // Always format

      // Pass namespace if defined, though MakeCrudCommand can also read it from config if we added it there.
      // But let's pass it just in case config structure in MakeCrudCommand expects it from option OR config.
      if (isset($data['namespace'])) {
        $options['--namespace'] = $data['namespace'];
      }

      $this->call('make:crud', $options);
      $this->line('');
    }

    $this->info("Multi-CRUD {$action} selesai!");

    return 0;
  }
}
