<?php

use App\Services\ComposerWorkspace;

it('creates a workspace composer file with the local path repository and cleans it up', function () {
    $projectDir = sys_get_temp_dir() . '/probots-cli-' . bin2hex(random_bytes(5));
    $themeDir = $projectDir . '/theme';
    mkdir($themeDir, 0777, true);

    file_put_contents($themeDir . '/composer.json', json_encode([
        'name' => 'probots/theme',
        'repositories' => [
            ['type' => 'composer', 'url' => 'https://packages.probots.io/'],
        ],
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

    config()->set('project.directory', $projectDir);

    $workspaceFile = ComposerWorkspace::createThemeComposerFile();
    $workspaceComposer = json_decode((string) file_get_contents($workspaceFile), true);

    expect($workspaceFile)->toBe($themeDir . '/.composer.workspace.json');
    expect($workspaceComposer['repositories'][0])->toBe([
        'type' => 'path',
        'url' => '/var/www/packages/package-*',
        'canonical' => false,
        'options' => [
            'symlink' => true,
            'versions' => [
                'probots/wordpress-package-cli' => '0.0.999',
                'probots/wordpress-package-debug' => '0.0.999',
            ],
        ],
    ]);

    ComposerWorkspace::cleanupThemeComposerFile();

    expect(file_exists($workspaceFile))->toBeFalse();

    unlink($themeDir . '/composer.json');
    rmdir($themeDir);
    rmdir($projectDir);
});

it('derives workspace versions from current probots package constraints', function () {
    $projectDir = sys_get_temp_dir() . '/probots-cli-' . bin2hex(random_bytes(5));
    $themeDir = $projectDir . '/theme';
    mkdir($themeDir, 0777, true);

    file_put_contents($themeDir . '/composer.json', json_encode([
        'require' => [
            'probots/wordpress-package-acf' => '4.0.*',
            'probots/wordpress-package-ai' => '^4.1',
            'probots/wordpress-package-base' => '~4.2.3',
            'probots/wordpress-package-blocks' => '*',
        ],
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

    config()->set('project.directory', $projectDir);

    $workspaceFile = ComposerWorkspace::createThemeComposerFile();
    $workspaceComposer = json_decode((string) file_get_contents($workspaceFile), true);

    expect($workspaceComposer['repositories'][0]['options']['versions'])->toBe([
        'probots/wordpress-package-acf' => '4.0.999',
        'probots/wordpress-package-ai' => '4.1.999',
        'probots/wordpress-package-base' => '4.2.3',
        'probots/wordpress-package-blocks' => '9999999-dev',
        'probots/wordpress-package-cli' => '0.0.999',
        'probots/wordpress-package-debug' => '0.0.999',
    ]);

    ComposerWorkspace::cleanupThemeComposerFile();

    unlink($themeDir . '/composer.json');
    rmdir($themeDir);
    rmdir($projectDir);
});
