<?php

namespace App\Support;

use Symfony\Component\Process\Process;
use Throwable;

class AppVersion
{
    public static function resolve(): string
    {
        $configuredVersion = env('APP_VERSION');

        if (is_string($configuredVersion) && $configuredVersion !== '' && strtolower($configuredVersion) !== 'auto') {
            return $configuredVersion;
        }

        $gitVersion = self::resolveFromGit();

        if ($gitVersion !== null) {
            return $gitVersion;
        }

        return '2.1.0';
    }

    private static function resolveFromGit(): ?string
    {
        if (!is_dir(base_path('.git'))) {
            return null;
        }

        $describe = self::runGitCommand(['describe', '--tags', '--always', '--dirty']);
        if ($describe !== null) {
            return $describe;
        }

        $commit = self::runGitCommand(['rev-parse', '--short', 'HEAD']);
        if ($commit !== null) {
            return 'dev-' . $commit;
        }

        return null;
    }

    private static function runGitCommand(array $arguments): ?string
    {
        try {
            $command = array_merge(['git'], $arguments);
            $process = new Process($command, base_path(), null, null, 2);
            $process->run();

            if (! $process->isSuccessful()) {
                return null;
            }

            $output = trim($process->getOutput());

            return $output !== '' ? $output : null;
        } catch (Throwable) {
            return null;
        }
    }
}
