<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreCategoryRequest;
use App\Http\Requests\Api\UpdateCategoryRequest;
use App\Http\Resources\Api\CategoryResource;
use App\Models\Category;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Category::query()->where('is_active', true)->orderBy('sort_order')->orderBy('name');
        if ($request->user()?->isAdmin()) {
            $query = Category::query()->orderBy('sort_order')->orderBy('name');
        }
        $categories = $query->get();

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

    public function store(StoreCategoryRequest $request): JsonResponse
    {
        $data = $request->validated();
        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('categories', 'public');
        }
        $category = Category::create($data);

        return response()->json(['data' => new CategoryResource($category)], 201);
    }

    public function show(Request $request, Category $category): JsonResponse
    {
        if (! $request->user()?->isAdmin() && ! $category->is_active) {
            abort(404);
        }

        return response()->json(['data' => new CategoryResource($category->loadCount('products'))]);
    }

    public function update(UpdateCategoryRequest $request, Category $category): JsonResponse
    {
        $data = $request->validated();
        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('categories', 'public');
        }
        $category->update($data);

        return response()->json(['data' => new CategoryResource($category->fresh())]);
    }

    public function destroy(Category $category): JsonResponse
    {
        $category->delete();

        return response()->json(['message' => __('Category deleted.')]);
    }
}
