<?php

declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));
date_default_timezone_set('Asia/Ho_Chi_Minh');

$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/Post.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));
$pdo->prepare(
    'INSERT INTO users (full_name, phone, email, password_hash, role)
     VALUES (?, ?, ?, ?, "owner")'
)->execute(['E2E Owner', '08' . random_int(10000000, 99999999), 'owner-' . $suffix . '@example.test', 'x']);
$ownerId = (int) $pdo->lastInsertId();
$pdo->prepare('INSERT INTO post_categories (name, slug, is_active) VALUES (?, ?, 1)')
    ->execute(['Chăm sóc E2E', 'cham-soc-e2e-' . $suffix]);
$categoryId = (int) $pdo->lastInsertId();

$posts = new Post();
$slug = 'bai-viet-e2e-' . $suffix;
$postId = $posts->create([
    'category_id' => $categoryId,
    'author_id' => $ownerId,
    'title' => 'Bài viết E2E',
    'slug' => $slug,
    'excerpt' => 'Chăm sóc thú cưng E2E',
    'content' => 'Nội dung E2E',
    'featured_image' => null,
    'status' => 'draft'
]);
if ($posts->findPublishedBySlug($slug) !== null) {
    throw new RuntimeException('Draft post leaked to public.');
}

$posts->updatePost($postId, [
    'category_id' => $categoryId,
    'title' => 'Bài viết E2E',
    'slug' => $slug,
    'excerpt' => 'Chăm sóc thú cưng E2E',
    'content' => 'Nội dung E2E',
    'featured_image' => null,
    'status' => 'published'
]);
if ($posts->findPublishedBySlug($slug) === null
    || count($posts->getPublished('chăm sóc', $categoryId, 10, 0)) !== 1) {
    throw new RuntimeException('Published post is not public/searchable.');
}

$posts->hide($postId);
if ($posts->findPublishedBySlug($slug) !== null) {
    throw new RuntimeException('Hidden post leaked to public.');
}

echo "POSTS E2E PASS: draft visibility, publish, detail/search/category, hide\n";
