<?php
declare(strict_types=1);

function mocker_migrate_site_news(PDO $pdo): void
{
    $pdo->exec(
        'CREATE TABLE IF NOT EXISTS site_news (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            summary TEXT NOT NULL DEFAULT "",
            body TEXT NOT NULL DEFAULT "",
            image_url TEXT NOT NULL DEFAULT "",
            published_at INTEGER NOT NULL,
            is_published INTEGER NOT NULL DEFAULT 1,
            sort_order INTEGER NOT NULL DEFAULT 0,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL
        )'
    );
    $pdo->exec(
        'CREATE INDEX IF NOT EXISTS idx_site_news_list ON site_news(is_published, sort_order DESC, published_at DESC)'
    );
}

/**
 * @param array<string, mixed> $row
 * @return array<string, mixed>
 */
function mocker_news_row_to_public(array $row, bool $includeBody = false): array
{
    $out = [
        'id' => (int) $row['id'],
        'title' => (string) $row['title'],
        'summary' => (string) $row['summary'],
        'imageUrl' => (string) $row['image_url'],
        'publishedAt' => (int) $row['published_at'],
        'sortOrder' => (int) $row['sort_order'],
    ];
    if ($includeBody) {
        $out['body'] = (string) $row['body'];
    }

    return $out;
}

function mocker_news_parse_published_at(mixed $raw): int
{
    if ($raw === null || $raw === '') {
        return time();
    }
    if (is_numeric($raw)) {
        $n = (int) $raw;

        return $n > 0 ? $n : time();
    }
    $s = trim((string) $raw);
    if ($s === '') {
        return time();
    }
    $t = strtotime($s);

    return ($t !== false && $t > 0) ? $t : time();
}
