<?php

namespace App\Http\Controllers\Api\V1\Category;

use App\Http\Controllers\Api\V1\Category\Resources\CategoryResource;
use App\Http\Controllers\Api\V1\Product\Resources\ProductResource;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Category\CategoryIndexRequest;
use App\Http\Requests\Api\V1\Product\BasicProductIndexRequest;
use App\Models\Ecommerce\Product\Category\Category;
use App\Repositories\Ecommerce\Product\Category\CategoryRepository;
use App\Repositories\Ecommerce\Product\ProductRepository;
use Illuminate\Http\JsonResponse;

class CategoryController extends Controller
{
    /**
     * Categories (index)
     */
    public function index(CategoryIndexRequest $request): JsonResponse
    {
        return response()->rest(
            CategoryResource::collection(
                CategoryRepository::make($request)
                    ->applyBasicQueries()
                    ->applyFilters()
                    ->get()
            )
        );
    }

    /**
     * Categories (show)
     */
    public function show(Category $category): JsonResponse
    {
        $category->load(['media', 'children']);

        return response()->rest(new CategoryResource($category));
    }

    /**
     * Categories (children)
     */
    public function children(Category $category): JsonResponse
    {
        return response()->rest(
            CategoryResource::collection(
                $category->children()
                    ->enabled()
                    ->ordered()
                    ->get()
            )
        );
    }

    /**
     * Brands (products)
     */
    public function products(BasicProductIndexRequest $request, Category $category): JsonResponse
    {
        return response()->rest_paginate(
            ProductResource::collection(
                ProductRepository::make($request)
                    ->queryAsFromResource($category)
                    ->applyBasicQueries()
                    ->applyFilters()
                    ->applySorting()
                    ->simplePaginate()
            )
        );
    }
}
