<?php

declare(strict_types=1);

class FrontFavoriteController
{
    public static function routes(): void
    {
        Router::get('/favorites', [self::class, 'index']);
        Router::post('/favorite/{id}/toggle', [self::class, 'toggle']);
    }

    public static function index(): void
    {
        Auth::requireAuth();
        $total = Favorite::userFavoritesCount(Auth::id());
        $pagination = Pagination::fromRequest($total, 24);

        ThemeRenderer::render('favorites', [
            'pageTitle' => SEO::title('My Favorites'),
            'videos' => Favorite::userFavorites(Auth::id(), 24, $pagination->offset),
            'pagination' => $pagination,
        ]);
    }

    public static function toggle(): void
    {
        if (!Router::verifyCsrf()) {
            Router::json(['error' => 'csrf_failed', 'message' => 'Your session has expired. Please refresh the page.'], 403);
        }

        if (!RateLimiter::throttle('fav', 60, 300)) {
            Router::json(['error' => 'rate_limit', 'message' => 'Too many requests. Please try again later.'], 429);
        }

        if (!Auth::check()) {
            Router::json(['error' => 'auth_required', 'message' => 'Please log in to perform this action.'], 401);
        }

        $videoId = (int) Router::param('id');
        $favorited = Favorite::toggle(Auth::id(), $videoId);

        Router::json(['favorited' => $favorited]);
    }
}
