<?php

declare(strict_types=1);

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

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

$metadata = new FakeMetadataProvider([
    'accounts' => ['id', 'name', 'account_type_id', 'sector_id', 'public_location_id', 'type', 'public_location', 'account_sector'],
    'contacts' => ['id', 'account_id', 'contact_email_1'],
]);

$parser = new DslParser();
$compiler = new DslCompiler($metadata);

$ast = $parser->parse("accounts and contacts where accounts.type = 'Member'");
$compiled = $compiler->compile($ast);
$sql = (string) ($compiled['sql'] ?? '');

if (strpos($sql, 'LEFT JOIN `picklist_account_type`') === false) {
    fwrite(STDERR, "Expected implicit join to picklist_account_type\n");
    exit(1);
}
if (strpos($sql, 'LEFT JOIN `picklist_public_location`') === false) {
    fwrite(STDERR, "Expected implicit join to picklist_public_location\n");
    exit(1);
}
if (strpos($sql, 'LEFT JOIN `picklist_sector`') === false) {
    fwrite(STDERR, "Expected implicit join to picklist_sector\n");
    exit(1);
}
if (strpos($sql, '`p_account_type`.`value` AS `accounts.type`') === false) {
    fwrite(STDERR, "Expected accounts.type projection from picklist_account_type.value\n");
    exit(1);
}
if (strpos($sql, '`p_public_location`.`value` AS `accounts.public_location`') === false) {
    fwrite(STDERR, "Expected accounts.public_location projection from picklist_public_location.value\n");
    exit(1);
}
if (strpos($sql, '`p_sector`.`value` AS `accounts.account_sector`') === false) {
    fwrite(STDERR, "Expected accounts.account_sector projection from picklist_sector.value\n");
    exit(1);
}
if (strpos($sql, '`p_account_type`.`value` = ?') === false) {
    fwrite(STDERR, "Expected predicate accounts.type to compile against picklist value\n");
    exit(1);
}

echo "DSL accounts picklist join regression test passed\n";

