<?php
declare(strict_types=1);

function mocker_migrate_site_notifications(PDO $pdo): void
{
    $pdo->exec(
        'CREATE TABLE IF NOT EXISTS site_notifications (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            body TEXT NOT NULL,
            link_url TEXT NOT NULL DEFAULT "",
            is_published INTEGER NOT NULL DEFAULT 1,
            created_at INTEGER NOT NULL,
            created_by TEXT NOT NULL DEFAULT ""
        )'
    );
    $pdo->exec(
        'CREATE INDEX IF NOT EXISTS idx_site_notifications_list
         ON site_notifications(is_published, created_at DESC)'
    );
    $pdo->exec(
        'CREATE TABLE IF NOT EXISTS user_notification_reads (
            user_id INTEGER NOT NULL,
            notification_id INTEGER NOT NULL,
            read_at INTEGER NOT NULL,
            PRIMARY KEY (user_id, notification_id),
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (notification_id) REFERENCES site_notifications(id) ON DELETE CASCADE
        )'
    );
}

/**
 * @param array<string, mixed> $row
 * @return array<string, mixed>
 */
function mocker_notification_row_to_public(array $row, bool $read): array
{
    $link = trim((string) ($row['link_url'] ?? ''));
    return [
        'id' => (int) $row['id'],
        'title' => (string) $row['title'],
        'body' => (string) $row['body'],
        'linkUrl' => $link,
        'createdAt' => (int) $row['created_at'],
        'read' => $read,
    ];
}

function mocker_notification_normalize_link(string $link): string
{
    $link = trim($link);
    if ($link === '') {
        return '';
    }
    if (preg_match('#^/#', $link)) {
        return $link;
    }
    if (preg_match('#^https?://#i', $link)) {
        return $link;
    }
    return '';
}
