<?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\Application\DslValidator;
use FecaMailshots\Domain\DslParser;
use FecaMailshots\Tests\Unit\FakeMetadataProvider;

$metadata = new FakeMetadataProvider([
    'contacts' => ['ID', 'Accountid', 'Last', 'Email', 'FENContact1', 'is_deleted'],
    'accounts' => ['ID', 'Name', 'Type', 'is_deleted'],
    'renewals' => ['id', 'account_id', 'status', 'selected'],
    'advertisers' => ['name', 'advertisername'],
    'ads' => ['id', 'advertiser', 'adsize', 'size', 'price', 'issue', 'pageid', 'state', 'notes'],
    'pages' => ['id', 'issue', 'page'],
    'articles' => ['id', 'pageid', 'articlenumber', 'article', 'content', 'membername', 'author', 'dcn', 'articlewords', 'otherwords', 'othercontent', 'other'],
    'issues' => ['id', 'issue', 'issuemonths', 'description'],
    'invoices' => ['id', 'issue', 'issue_id', 'ad_id', 'invoice_number', 'status'],
    'members.ExcludedAccounts' => ['ExcludedAccount'],
    'fenedgec_members.renewal_accounts_with_contacts' => ['renewal_id', 'account_id', 'contact_1_phone_1'],
]);

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

$cases = [
    [
        'dsl' => "contacts and accounts where contacts.Last contains 'smith' and contacts.Accountid = accounts.ID",
        'expectValid' => true,
    ],
    [
        'dsl' => 'accounts where pending-renewal',
        'expectValid' => false,
    ],
    [
        'dsl' => 'contacts and members.ExcludedAccounts',
        'expectValid' => false,
    ],
    [
        'dsl' => 'ads and pages where issue(202605)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'articles and pages where issue(202605)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'invoices and ads where invoice-ids(10, 11)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'invoices and ads and pages and advertisers where issue(125)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'ads where issue(202605)',
        'expectValid' => true,
    ],
    [
        'dsl' => "invoices where invoice-ids('abc')",
        'expectValid' => false,
    ],
    [
        'dsl' => 'fenedgec_members.renewal_accounts_with_contacts',
        'expectValid' => true,
    ],
    [
        'dsl' => 'fenedgec_members.renewal_accounts_with_contacts where fenedgec_members.renewal_accounts_with_contacts.contact_1_phone_1 blank',
        'expectValid' => true,
    ],
    [
        'dsl' => 'issues where issue(202605)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'articles where issue(202605)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'advertisers where issue(202605)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'pages where ad-in-issue(202605)',
        'expectValid' => false,
    ],
    [
        'dsl' => 'contacts and accounts and issues where fen1-contact and issue(125)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'contacts and accounts and issues where fen1-contact',
        'expectValid' => false,
    ],
    [
        'dsl' => 'contacts and accounts and issues where fen1-contact and issue(125) and member-or-affiliate-or-parish-council and not account-has-article-in-issue(125)',
        'expectValid' => true,
    ],
    [
        'dsl' => 'contacts where account-has-article-in-issue(125)',
        'expectValid' => false,
    ],
];

$failures = [];

foreach ($cases as $case) {
    $ast = $parser->parse($case['dsl']);
    $validation = $validator->validate($ast);
    $isValid = $validation['errors'] === [];

    if ($isValid !== $case['expectValid']) {
        $failures[] = ['dsl' => $case['dsl'], 'errors' => $validation['errors']];
        continue;
    }

    if ($isValid) {
        $compiled = $compiler->compile($ast);
        if (strpos($compiled['sql'], 'SELECT ') !== 0) {
            $failures[] = ['dsl' => $case['dsl'], 'errors' => ['Compilation did not produce SELECT']];
        }
    }
}

if ($failures !== []) {
    fwrite(STDERR, "DSL pipeline test failures:\n" . json_encode($failures, JSON_PRETTY_PRINT) . "\n");
    exit(1);
}

echo "DSL pipeline tests passed\n";
