<?php

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

use App\Http\Controllers\Api\V1\Channel\Requests\ChannelIndexRequest;
use App\Http\Controllers\Api\V1\Product\Resources\ProductResource;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\V1\Channel\ChannelResource;
use App\Models\Ecommerce\Channel\Channel;
use App\Repositories\Ecommerce\Product\ProductRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ChannelController extends Controller
{
    /**
     * Channels (index)
     */
    public function index(ChannelIndexRequest $request): JsonResponse
    {
        return response()->rest_paginate(
            ChannelResource::collection(
                Channel::query()
                    ->with('media')
                    ->where('is_visible', true)
                    ->ordered()
                    ->simplePaginate(
                        perPage: $request->perPage,
                        columns: $request->fields,
                    )
            )
        );
    }

    /**
     * Channels (show)
     */
    public function show(Channel $channel): JsonResponse
    {
        $channel->load('media');

        return response()->rest(new ChannelResource($channel));
    }

    /**
     * Channels (products)
     */
    public function products(Request $request, Channel $channel): JsonResponse
    {
        return response()->rest_paginate(
            ProductResource::collection(
                ProductRepository::make($request)
                    ->queryAsFromResource($channel)
                    ->applyBasicQueries()
                    ->applyFilters()
                    ->applySorting()
                    ->simplePaginate()
            )
        );
    }
}
