<?php

function economic_ean_openapi_content_or_skip(): string
{
    $candidates = [];
    for ($depth = 1; $depth <= 8; $depth++) {
        $candidates[] = dirname(__DIR__, $depth) . DIRECTORY_SEPARATOR . 'openapi.yaml';
    }

    $cwd = getcwd();
    if (is_string($cwd) && $cwd !== '') {
        $candidates[] = $cwd . DIRECTORY_SEPARATOR . 'openapi.yaml';
        $candidates[] = dirname($cwd) . DIRECTORY_SEPARATOR . 'openapi.yaml';
    }

    foreach (array_values(array_unique($candidates)) as $candidate) {
        if (is_file($candidate)) {
            $content = file_get_contents($candidate);
            if ($content !== false) {
                return $content;
            }
        }
    }

    test()->markTestSkipped('openapi.yaml is not available in this runtime environment.');
}

function economic_ean_openapi_block(string $content, string $start, string $end): string
{
    $start_pos = strpos($content, $start);
    $end_pos = strpos($content, $end);
    expect($start_pos)->not->toBeFalse();
    expect($end_pos)->not->toBeFalse();
    expect($end_pos)->toBeGreaterThan($start_pos);

    return substr($content, (int)$start_pos, (int)$end_pos - (int)$start_pos);
}

it('documents optional EAN on customer creation endpoints', function (): void {
    $content = economic_ean_openapi_content_or_skip();

    $register_block = economic_ean_openapi_block($content, '/auth/register/cvr:', '/auth/password-reset/request:');
    $economic_customer_block = economic_ean_openapi_block($content, '/modules/economic/customer:', '/economic/layouts:');

    foreach ([$register_block, $economic_customer_block] as $block) {
        expect($block)->toContain('ean:');
        expect($block)->toContain('maxLength: 13');
        expect($block)->toContain("pattern: '^[0-9]{1,13}$'");
    }
});
