<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryApiController extends Controller
{
    /**
     * Get list of visible categories.
     */
    public function index()
    {
        $categories = \Illuminate\Support\Facades\Cache::remember('categories_list', 300, function () {
            return Category::where('is_visible', true)
                ->with('media') // Eager load media relationship to avoid N+1 query overhead
                ->orderBy('name')
                ->get()
                ->map(function ($category) {
                    // Fetch the uploaded image from Spatie Media Library
                    $category->image_url = $category->getFirstMediaUrl('image', 'webp')
                        ?: ($category->getFirstMediaUrl('image')
                        ?: null);
                    return $category;
                })
                ->toArray();
        });

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