<?php

declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/feca_mailshots_plugin/src/autoload.php';
require_once __DIR__ . '/FakeMetadataProvider.php';

use FecaMailshots\Application\DslValidator;
use FecaMailshots\Domain\DslParser;
use FecaMailshots\Tests\Unit\FakeMetadataProvider;

$metadata = new FakeMetadataProvider([
    'contacts' => ['ID', 'Accountid', 'Last', 'Email', 'FENContact1'],
    'accounts' => ['ID', 'Name', 'Type'],
]);

$parser = new DslParser();
$validator = new DslValidator($metadata);

$ast = $parser->parse('contacts and accounts where contacts.Accountid = accounts.ID');
$validation = $validator->validate($ast);

if ($validation['errors'] !== []) {
    fwrite(STDERR, 'Expected no validation errors, got: ' . json_encode($validation['errors']) . "\n");
    exit(1);
}

$expected = [
    'contacts.ID',
    'contacts.Accountid',
    'contacts.Last',
    'contacts.Email',
    'contacts.FENContact1',
    'accounts.ID',
    'accounts.Name',
    'accounts.Type',
];

sort($expected);
$actual = $validation['expected_fields'];
sort($actual);

if ($actual !== $expected) {
    fwrite(STDERR, 'Expected-field contract mismatch\n');
    fwrite(STDERR, 'Expected: ' . json_encode($expected) . "\n");
    fwrite(STDERR, 'Actual: ' . json_encode($actual) . "\n");
    exit(1);
}

echo "Preview shape contract test passed\n";
