<?php

namespace App\Actions\Init;

use App\Services\Docker;
use Illuminate\Support\Facades\Process;

class InstallProject
{
    public function handle(string $projectDir): void
    {
        $this->runOrFail(Docker::base('up -d'), $projectDir);
        $this->runOrFail(Docker::exec('composer install', config('project.publicCwd')), $projectDir);
        $this->runOrFail(Docker::exec('composer install', config('project.themeCwd') . '/theme'), $projectDir);
        $this->runOrFail(Docker::exec('yarn install', config('project.themeCwd') . '/theme'), $projectDir);
        $this->runOrFail(Docker::exec('./bin/install.sh'), $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);
        }
    }
}
