<?php

declare(strict_types=1);

class Favorite
{
    public static function toggle(int $userId, int $videoId): bool
    {
        return Database::transaction(function () use ($userId, $videoId): bool {
            $existing = Database::fetchOne(
                'SELECT 1 FROM user_favorites WHERE user_id = ? AND video_id = ? FOR UPDATE',
                [$userId, $videoId]
            );

            if ($existing) {
                Database::delete('user_favorites', 'user_id = ? AND video_id = ?', [$userId, $videoId]);
                Database::query('UPDATE videos SET favorites_count = GREATEST(0, favorites_count - 1) WHERE id = ?', [$videoId]);
                return false;
            }

            Database::insert('user_favorites', ['user_id' => $userId, 'video_id' => $videoId]);
            Database::query('UPDATE videos SET favorites_count = favorites_count + 1 WHERE id = ?', [$videoId]);
            return true;
        });
    }

    public static function isFavorited(int $userId, int $videoId): bool
    {
        return Database::fetchOne(
            'SELECT 1 FROM user_favorites WHERE user_id = ? AND video_id = ?',
            [$userId, $videoId]
        ) !== null;
    }

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

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