<?php

namespace App\Actions\Init;

use Illuminate\Support\Facades\Process;

class InitializeGit
{
    public function handle(string $projectDir, string $repositoryUrl): void
    {
        $this->runOrFail('git init', $projectDir);

        if ($repositoryUrl !== '') {
            $this->runOrFail(sprintf('git remote add origin %s', escapeshellarg($repositoryUrl)), $projectDir);
        }

        $this->runOrFail('git add .', $projectDir);
        $this->runOrFail('git commit -m "Initial commit"', $projectDir);
        $this->runOrFail('git flow init -d', $projectDir);
    }

    private function runOrFail(string $command, string $path): void
    {
        $result = Process::path($path)->run($command);

        if (!$result->successful()) {
            $message = trim($result->errorOutput()) ?: trim($result->output()) ?: 'Unknown process failure.';

            throw new \RuntimeException($message);
        }
    }
}
