<?php

namespace Modules\User\Http\Controllers\Api\Favorite;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jason\Api\Api;
use Modules\Cms\Http\Resources\CategoryCollection;
use Modules\Cms\Models\Article;
use Modules\Cms\Models\Category;
use Modules\User\Http\Resources\Favorite\FavoriteCollection;

class IndexController extends Controller
{

    /**
     * Notes: 我的收藏
     *
     * @Author: 玄尘
     * @Date: 2022/10/11 11:12
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $user            = Api::user();
        $category_id     = $request->category_id ?? 0;
        $favorteArticles = $user->favorites()
            ->when($category_id, function ($q) use ($category_id) {
                $q->whereHasMorph('favoriteable', [Article::class], function ($query) use ($category_id) {
                    $query->whereHas('categories', function ($q) use ($category_id) {
                        $q->where('cms_categories.id', $category_id);
                    });
                });
            })
            ->paginate();

        $data = [
            'categories' => new CategoryCollection(Category::query()->get()),
            'favorites'  => new FavoriteCollection($favorteArticles),
        ];
        return $this->success($data);
    }

}
