<?php

namespace App\Http\Controllers\Api\Inventory;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Inventory\SupplyCategoryStoreRequest;
use App\Http\Requests\Inventory\SupplyCategoryUpdateRequest;
use App\Http\Resources\Inventory\SupplyCategoryResource;
use App\Services\Inventory\SupplyCategoryService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class SupplyCategoryController extends BaseApiController
{
    public function __construct(private SupplyCategoryService $categories)
    {
        parent::__construct();
    }

    public function index(): JsonResponse
    {
        $rows = $this->categories->list();

        return $this->success([
            'categories' => SupplyCategoryResource::collection($rows),
        ]);
    }

    public function store(SupplyCategoryStoreRequest $request): JsonResponse
    {
        $result = $this->categories->create($request->validated());
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to save category.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->respondCreated(new SupplyCategoryResource($result['category']));
    }

    public function update(SupplyCategoryUpdateRequest $request, int $id): JsonResponse
    {
        $result = $this->categories->update($id, $request->validated());
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to update category.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success(new SupplyCategoryResource($result['category']));
    }

    public function destroy(int $id): JsonResponse
    {
        $result = $this->categories->delete($id);
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to delete category.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->respondDeleted();
    }
}
