<?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 outside an isolated pet_shop_e2e_* database.');
}

require_once BASE_PATH . '/config/database.php';
require_once BASE_PATH . '/app/models/Contact.php';
require_once BASE_PATH . '/app/models/User.php';
require_once BASE_PATH . '/app/models/Notification.php';

$pdo = (new Database())->connect();
if ($pdo->query('SELECT DATABASE()')->fetchColumn() !== $testDatabase) {
    throw new RuntimeException('Wrong test database.');
}
$suffix = bin2hex(random_bytes(4));
$pdo->prepare('INSERT INTO users (full_name, phone, email, password_hash, role) VALUES (?, ?, ?, ?, "owner")')
    ->execute(['E2E Contact Owner', '05' . random_int(10000000, 99999999), 'contact-owner-' . $suffix . '@example.test', 'x']);
$ownerId = (int) $pdo->lastInsertId();
$contactId = (new Contact())->create(['full_name' => 'Khách E2E', 'phone' => '0900000000', 'email' => 'contact-' . $suffix . '@example.test', 'subject' => 'Tư vấn', 'message' => 'Vui lòng liên hệ lại.']);
foreach ((new User())->getActiveOwnerIds() as $id) {
    (new Notification())->create($id, 'contact.created', 'Có liên hệ mới', 'Khách E2E vừa gửi một lời nhắn.', '?url=owner/contact&id=' . $contactId);
}
$notification = $pdo->prepare('SELECT link FROM notifications WHERE user_id = ? AND type = "contact.created" ORDER BY id DESC LIMIT 1');
$notification->execute([$ownerId]);
if ($notification->fetchColumn() !== '?url=owner/contact&id=' . $contactId) {
    throw new RuntimeException('Owner contact notification is missing or has a dead link.');
}
echo "CONTACT E2E PASS: contact inbox record and Owner notification link\n";
