<?php

declare(strict_types=1);

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

use FecaMailshots\Application\PerUserMailCredentialsProvider;
use FecaMailshots\Infrastructure\PdoDatabaseRouter;
use FecaMailshots\Infrastructure\WordPressSaltSecretKeyProvider;
use FecaMailshots\Infrastructure\Env;
use FecaMailshots\Repository\MailCredentialRepository;
use FecaMailshots\WordPress\FixtureWordPressFacade;

if (!defined('AUTH_KEY')) define('AUTH_KEY', 'phase-auth');
if (!defined('SECURE_AUTH_KEY')) define('SECURE_AUTH_KEY', 'phase-secure');
if (!defined('LOGGED_IN_KEY')) define('LOGGED_IN_KEY', 'phase-logged');
if (!defined('NONCE_KEY')) define('NONCE_KEY', 'phase-nonce');

Env::load(dirname(__DIR__, 2) . '/credentials/.env');

$dbConfig = [
    'MYSQL_HOST' => '127.0.0.1',
    'MYSQL_PORT' => (string) (getenv('MYSQL_TUNNEL_LOCAL_PORT') ?: '13306'),
    'MYSQL_USER' => Env::require('REMOTE_MYSQL_USER'),
    'MYSQL_PASSWORD' => Env::require('REMOTE_MYSQL_PASSWORD'),
    'MAILSHOTS_REMOTE_MYSQL_DB' => Env::require('MAILSHOTS_REMOTE_MYSQL_DB'),
    'MEMBERS_REMOTE_MYSQL_DB' => Env::require('MEMBERS_REMOTE_MYSQL_DB'),
    'FEN_REMOTE_MYSQL_DB' => Env::require('FEN_REMOTE_MYSQL_DB'),
];

$router = new PdoDatabaseRouter($dbConfig);
$repo = new MailCredentialRepository($router, new WordPressSaltSecretKeyProvider());
$wp = new FixtureWordPressFacade();
$provider = new PerUserMailCredentialsProvider($repo, $wp);

$userA = 101;
$userB = 102;
try {
$repo->upsertForUser($userA, [
    'smtp_host' => 'smtp.usera.example',
    'smtp_port' => 587,
    'smtp_user' => 'usera',
    'smtp_password' => 'secret-a',
    'smtp_from_email' => 'usera@example.org',
    'smtp_from_name' => 'User A',
    'smtp_require_tls' => false,
    'imap_host' => 'imap.usera.example',
    'imap_port' => 993,
    'imap_user' => 'usera',
    'imap_password' => 'imap-a',
    'imap_sent_folder' => 'Sent',
    'imap_mailbox_flags' => '/imap/ssl',
]);

$repo->upsertForUser($userB, [
    'smtp_host' => 'smtp.userb.example',
    'smtp_port' => 587,
    'smtp_user' => 'userb',
    'smtp_password' => 'secret-b',
    'smtp_from_email' => 'userb@example.org',
    'smtp_from_name' => 'User B',
    'smtp_require_tls' => true,
    'imap_host' => 'imap.userb.example',
    'imap_port' => 993,
    'imap_user' => 'userb',
    'imap_password' => 'imap-b',
    'imap_sent_folder' => 'Sent',
    'imap_mailbox_flags' => '/imap/ssl',
]);

$pdo = $router->mailshotsPdo();
$stmt = $pdo->prepare('SELECT smtp_password_enc FROM mailshot_credentials WHERE wp_user_id = :uid');
$stmt->execute(['uid' => $userA]);
$encA = (string) $stmt->fetchColumn();
if ($encA === '' || str_contains($encA, 'secret-a')) {
    fwrite(STDERR, "Expected encrypted smtp password for user A\n");
    exit(1);
}

$wp->setCurrentUserId($userA);
$credsA = $provider->credentials();
if (!is_array($credsA) || (string) ($credsA['smtp_user'] ?? '') !== 'usera' || (string) ($credsA['smtp_password'] ?? '') !== 'secret-a') {
    fwrite(STDERR, "Per-user credentials resolution failed for user A\n");
    exit(1);
}

$wp->setCurrentUserId($userB);
$credsB = $provider->credentials();
if (!is_array($credsB) || (string) ($credsB['smtp_user'] ?? '') !== 'userb' || (string) ($credsB['smtp_password'] ?? '') !== 'secret-b') {
    fwrite(STDERR, "Per-user credentials resolution failed for user B\n");
    exit(1);
}

echo "Per-user encrypted credential integration test passed\n";
} finally {
    try { $router->mailshotsPdo()->prepare('DELETE FROM mailshot_credentials WHERE wp_user_id = :uid')->execute(['uid' => $userA]); } catch (Throwable $e) {}
    try { $router->mailshotsPdo()->prepare('DELETE FROM mailshot_credentials WHERE wp_user_id = :uid')->execute(['uid' => $userB]); } catch (Throwable $e) {}
}
