<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Repositories\Contracts\CategoryRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use OpenApi\Attributes as OA;

class CategoryController extends Controller
{
    public function __construct(private CategoryRepositoryInterface $repository) {}

    #[OA\Get(
        path: '/api/v1/categories',
        summary: 'Kategorileri listele',
        description: 'Tüm aktif kategorileri sayfalanmış olarak döndürür.',
        tags: ['Categories'],
        parameters: [
            new OA\Parameter(name: 'search', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'per_page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 15)),
        ],
        responses: [
            new OA\Response(response: 200, description: 'Kategori listesi'),
        ],
    )]
    public function index(Request $request): AnonymousResourceCollection
    {
        $categories = $this->repository->paginate(
            filters: $request->only('search'),
            perPage: $request->integer('per_page', 15),
        );

        return CategoryResource::collection($categories);
    }

    #[OA\Get(
        path: '/api/v1/categories/{slug}',
        summary: 'Kategori detayı',
        description: 'Slug ile kategori detayını döndürür.',
        tags: ['Categories'],
        parameters: [
            new OA\Parameter(name: 'slug', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
        ],
        responses: [
            new OA\Response(response: 200, description: 'Kategori detayı'),
            new OA\Response(response: 404, description: 'Kategori bulunamadı'),
        ],
    )]
    public function show(string $slug): CategoryResource
    {
        $category = $this->repository->findBySlug($slug);

        abort_if(! $category, 404, 'Kategori bulunamadı.');

        return new CategoryResource($category);
    }
}
