<?php

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

use App\Http\Controllers\Api\V1\Brand\Resources\BrandResource;
use App\Http\Controllers\Api\V1\Product\Resources\ProductResource;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Brand\BrandIndexRequest;
use App\Http\Requests\Api\V1\Brand\BrandProductsRequest;
use App\Models\Ecommerce\Product\Brand\Brand;
use App\Repositories\Ecommerce\Product\ProductRepository;
use Illuminate\Http\JsonResponse;

class BrandController extends Controller
{
    /**
     * Brands (index)
     */
    public function index(BrandIndexRequest $request): JsonResponse
    {
        return response()->rest(
            BrandResource::collection(
                Brand::query()
                    ->with('media')
                    ->enabled()
                    ->ordered()
                    ->when($request->input('type'), fn ($query, $type) => $query->where('type', $type))
                    ->get()
            )
        );
    }

    /**
     * Brands (show)
     *
     * @param  App\Models\Ecommerce\Product\Brand\Brand  $brand
     */
    public function show(Brand $brand): JsonResponse
    {
        $brand->load('media');

        return response()->rest(new BrandResource($brand));
    }

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