<?php

namespace App\Commands;

use App\Services\Command;
use App\Services\ComposerWorkspace;
use App\Services\Docker;
use Illuminate\Support\Facades\Process;
use function config;
use function Laravel\Prompts\select;

class Composer extends Command
{
    protected $signature = 'composer 
        {commands* : The composer command to run}
        {--workspace : Use local workspace package paths for theme commands}';

    protected $description = 'Run composer within the container';

    public function handle() : void
    {

        $cmd = $this->argument('commands');
        $themeName = config('project.env')->get('THEME_NAME');

        $targetDir = select(
            label: 'Where do you want to run the command?',
            options: ['theme' => 'in Theme', 'root' => 'in Root'],
            default: 'theme'
        );

        $cwd = match ($targetDir) {
            'root'  => config('project.publicCwd'),
            default => sprintf('%s/%s', config('project.themeCwd'), $themeName),
        };

        $composerPrefix = 'composer';

        if ($this->option('workspace') && $targetDir === 'theme') {
            ComposerWorkspace::createThemeComposerFile();
            $composerPrefix = sprintf('COMPOSER=%s/.composer.workspace.json composer', $cwd);
        }

        if ($this->option('workspace') && $targetDir !== 'theme') {
            $this->warn('Ignoring --workspace for root Composer commands.');
        }

        $shellCommand = Docker::exec(
            command: sprintf('%s %s', $composerPrefix, implode(' ', $cmd)),
            cwd: $cwd
        );

        try {
            Process::forever()->run($shellCommand, function (string $type, string $output) {
                echo $output;
            });
        } finally {
            ComposerWorkspace::cleanupThemeComposerFile();
        }
    }

}
