<?php

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

use App\Http\Controllers\Api\V1\Collection\Resources\CollectionResource;
use App\Http\Controllers\Api\V1\Product\Resources\ProductResource;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Product\BasicProductIndexRequest;
use App\Models\Ecommerce\Product\Collection\Collection;
use App\Repositories\Ecommerce\Product\ProductRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CollectionController extends Controller
{
    /**
     * Collections (index).
     */
    public function index(): JsonResponse
    {
        return response()->rest(
            CollectionResource::collection(
                Collection::with('media')->where('is_visible', true)->ordered()->get()
            )
        );
    }

    /**
     * Paginated
     */
    public function paginated(Request $request)
    {
        $perPage = $request->perPage ?: 6;

        return response()->rest_paginate(
            CollectionResource::collection(
                Collection::with('media')->where('is_visible', true)->ordered()->simplePaginate($perPage)
            )
        );
    }

    /**
     * Collections (show)
     */
    public function show(Collection $collection): JsonResponse
    {
        $collection->load('media');

        return response()->rest(new CollectionResource($collection));
    }

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