<?php

declare(strict_types=1);

class History
{
    public static function record(int $userId, int $videoId): void
    {
        Database::query(
            'INSERT INTO user_history (user_id, video_id, watched_at) VALUES (?, ?, NOW())
             ON DUPLICATE KEY UPDATE watched_at = NOW()',
            [$userId, $videoId]
        );
    }

    public static function userHistory(int $userId, int $limit = 24, int $offset = 0): array
    {
        $results = Database::fetchAll(
            "SELECT v.*, uh.watched_at
             FROM videos v
             JOIN user_history uh ON v.id = uh.video_id
             WHERE uh.user_id = ? AND v.status = ?
             ORDER BY uh.watched_at DESC LIMIT ? OFFSET ?",
            [$userId, 'published', $limit, $offset]
        );
        return Video::localizeResults($results);
    }

    public static function userHistoryCount(int $userId): int
    {
        return Database::count('user_history', 'user_id = ?', [$userId]);
    }

    public static function clear(int $userId): void
    {
        Database::delete('user_history', 'user_id = ?', [$userId]);
    }
}
