<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

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

class TagController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json([
            'data' => Tag::query()->orderByDesc('use_count')->get(['id', 'name', 'use_count']),
        ]);
    }

    public function articles(Request $request, string $name, BlogSettings $blog): JsonResponse
    {
        $tag = Tag::query()->where('name', $name)->firstOrFail();
        $perPage = max(1, min(50, $request->integer('per_page') ?: $blog->posts_per_page));

        $articles = $tag->articles()
            ->with(['category:id,name'])
            ->visible()
            ->published()
            ->orderByDesc('published_at')
            ->paginate($perPage);

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