<?php

declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));

$testDatabase = (string) getenv('PET_SPA_TEST_DB');
if (!preg_match('/^pet_shop_e2e_[a-z0-9_]+$/', $testDatabase)) {
    throw new RuntimeException('Refusing to run: use an isolated pet_shop_e2e_* database.');
}

require_once BASE_PATH . '/config/database.php';
require_once BASE_PATH . '/app/models/User.php';
require_once BASE_PATH . '/app/models/PasswordReset.php';
require_once BASE_PATH . '/app/models/SystemSetting.php';

$database = new Database();
$pdo = $database->connect();
if ($database->databaseName() !== $testDatabase
    || $pdo->query('SELECT DATABASE()')->fetchColumn() !== $testDatabase
    || $testDatabase === 'pet_shop') {
    throw new RuntimeException('Refusing destructive E2E test against the main database.');
}

$suffix = bin2hex(random_bytes(4));
$phone = '07' . random_int(10000000, 99999999);
$email = 'customer-' . $suffix . '@example.test';
$users = new User();
$userId = $users->createCustomer([
    'full_name' => 'E2E Customer',
    'phone' => $phone,
    'email' => $email,
    'password_hash' => password_hash('password-e2e', PASSWORD_DEFAULT)
]);
$emailUser = $users->findByIdentifier($email);
$phoneUser = $users->findByIdentifier($phone);
if (!$emailUser || !$phoneUser || !password_verify('password-e2e', $emailUser['password_hash'])) {
    throw new RuntimeException('Email/phone authentication lookup failed.');
}
$pdo->prepare('UPDATE users SET status = "locked" WHERE id = ?')->execute([$userId]);
if (($users->findByIdentifier($email)['status'] ?? '') !== 'locked') {
    throw new RuntimeException('Locked-account status check failed.');
}
$pdo->prepare('UPDATE users SET status = "active" WHERE id = ?')->execute([$userId]);

$resets = new PasswordReset();
$token = $resets->createForUser($userId);
if (!$resets->isValidToken($token) || $resets->resetPassword($token, password_hash('new-password-e2e', PASSWORD_DEFAULT)) !== $userId || $resets->isValidToken($token)) {
    throw new RuntimeException('Password reset flow failed.');
}

$settings = new SystemSetting();
$settings->update(['registration_enabled' => '0'], $userId);
if ($settings->getBoolean('registration_enabled', true)) {
    throw new RuntimeException('Registration disable setting failed.');
}
$settings->update(['registration_enabled' => '1'], $userId);

echo "AUTH MODEL E2E PASS: register data, email/phone lookup, lock state, reset, registration setting\n";
