<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\Category;
use App\Settings\BlogSettings;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index(): JsonResponse
    {
        $categories = Category::query()->orderBy('display_order')->get(['id', 'name', 'articles_count', 'display_order']);

        return response()->json([
            'data' => $categories,
        ]);
    }

    public function articles(Request $request, int $id, BlogSettings $blog): JsonResponse
    {
        Category::query()->findOrFail($id);
        $perPage = max(1, min(50, $request->integer('per_page') ?: $blog->posts_per_page));

        $articles = Article::query()
            ->with(['category:id,name', 'tags:id,name'])
            ->visible()
            ->published()
            ->where('category_id', $id)
            ->orderByDesc('published_at')
            ->paginate($perPage);

        return response()->json([
            'data' => $articles->items(),
            'meta' => [
                'current_page' => $articles->currentPage(),
                'last_page' => $articles->lastPage(),
                'per_page' => $articles->perPage(),
                'total' => $articles->total(),
            ],
        ]);
    }
}
