<?php

namespace App\Services;

use function config;

class Docker
{

    protected static function composeFiles(): array
    {
        $composeFiles = config('project.compose_files', []);

        if (!$composeFiles) {
            return [config('project.compose_file')];
        }

        return array_values(array_filter($composeFiles));
    }

    public static function base(?string $command = null): string
    {
        $commandString = $command ? ' ' . $command : '';

        $composeFiles = implode(' ', array_map(static fn(string $file) => '-f ' . $file, self::composeFiles()));

        return sprintf('docker compose %s%s', $composeFiles, $commandString);
    }

    public static function exec(?string $command = null, string $cwd = null): string
    {
        $base = self::base();
        $dockerCwd = $cwd ?? config('project.dockerCwd');
        $user = config('project.dockerUser');
        $serviceName = config('project.serviceName');
        $shell = config('project.shell');
        $commandString = $command ? '-c "' . $command . '"' : '';

        return sprintf('%s exec -w %s --user %s %s %s %s',
            $base,
            $dockerCwd,
            $user,
            $serviceName,
            $shell,
            $commandString
        );
    }

    public static function bin(string $name): string
    {
        return self::exec(sprintf('./bin/%s.sh', $name));

    }

}
