<?php

namespace App\Http\Controllers\Api\Inventory;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Inventory\InventoryCategoryIndexRequest;
use App\Http\Requests\Inventory\InventoryCategoryStoreRequest;
use App\Http\Requests\Inventory\InventoryCategoryUpdateRequest;
use App\Http\Resources\Inventory\InventoryCategoryResource;
use App\Services\Inventory\InventoryCategoryService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

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

    public function index(InventoryCategoryIndexRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $rows = $this->categories->list($payload['type'] ?? null);

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

    public function store(InventoryCategoryStoreRequest $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 InventoryCategoryResource($result['category']));
    }

    public function update(InventoryCategoryUpdateRequest $request, int $id): JsonResponse
    {
        try {
            $result = $this->categories->update($id, $request->validated());
        } catch (\InvalidArgumentException $e) {
            return $this->error($e->getMessage(), Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to update category.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success(new InventoryCategoryResource($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();
    }
}
