<?php

namespace App\Services;

use function config;

class ComposerWorkspace
{
    public static function createThemeComposerFile(): string
    {
        $themeDir = sprintf('%s/theme', config('project.directory'));
        $baseComposerFile = sprintf('%s/composer.json', $themeDir);
        $workspaceComposerFile = sprintf('%s/.composer.workspace.json', $themeDir);

        if (!file_exists($baseComposerFile)) {
            throw new \RuntimeException(sprintf('Could not find %s', $baseComposerFile));
        }

        $composer = json_decode(file_get_contents($baseComposerFile), true, 512, JSON_THROW_ON_ERROR);
        $repositories = $composer['repositories'] ?? [];

        array_unshift($repositories, [
            'type' => 'path',
            'url' => '/var/www/packages/package-*',
            'canonical' => false,
            'options' => [
                'symlink' => true,
                'versions' => [
                    'probots/wordpress-package-acf' => '0.1.999',
                    'probots/wordpress-package-ai' => '0.1.999',
                    'probots/wordpress-package-base' => '3.1.999',
                    'probots/wordpress-package-blocks' => '2.2.999',
                    'probots/wordpress-package-cli' => '0.0.999',
                    'probots/wordpress-package-config' => '0.1.999',
                    'probots/wordpress-package-debug' => '0.0.999',
                    'probots/wordpress-package-multilang' => '0.1.999',
                    'probots/wordpress-package-seo' => '1.1.999',
                    'probots/wordpress-package-social' => '1.0.999',
                ],
            ],
        ]);

        $composer['repositories'] = $repositories;

        file_put_contents(
            $workspaceComposerFile,
            json_encode($composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL,
        );

        return $workspaceComposerFile;
    }

    public static function cleanupThemeComposerFile(): void
    {
        $workspaceComposerFile = sprintf('%s/theme/.composer.workspace.json', config('project.directory'));

        if (file_exists($workspaceComposerFile)) {
            unlink($workspaceComposerFile);
        }
    }
}
