<?php

namespace App\Http\Controllers\Api\V1\Product;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Product\StoreCategoryRequest;
use App\Http\Requests\Api\V1\Product\UpdateCategoryRequest;
use App\Services\CategoryService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;

class CategoryController extends Controller
{
    public function __construct(
        protected CategoryService $categoryService,
        protected ResponseService $responseService
    ) {}

    public function index(): JsonResponse
    {
        $categories = $this->categoryService->getAll();
        return $this->responseService->success($categories, 'Categories retrieved successfully');
    }

    public function active(): JsonResponse
    {
        $categories = $this->categoryService->getActive();
        return $this->responseService->success($categories, 'Active categories retrieved successfully');
    }

    public function withProducts(): JsonResponse
    {
        $categories = $this->categoryService->getWithProducts();
        return $this->responseService->success($categories, 'Categories with products retrieved successfully');
    }

    public function store(StoreCategoryRequest $request): JsonResponse
    {
        $category = $this->categoryService->create($request->validated());
        return $this->responseService->success($category, 'Category created successfully', 201);
    }

    public function show(int $id): JsonResponse
    {
        $category = $this->categoryService->find($id);

        if (!$category) {
            return $this->responseService->error('Category not found', 404);
        }

        return $this->responseService->success($category, 'Category retrieved successfully');
    }

    public function update(UpdateCategoryRequest $request, int $id): JsonResponse
    {
        $category = $this->categoryService->find($id);

        if (!$category) {
            return $this->responseService->error('Category not found', 404);
        }

        $category = $this->categoryService->update($id, $request->validated());
        return $this->responseService->success($category, 'Category updated successfully');
    }

    public function destroy(int $id): JsonResponse
    {
        $category = $this->categoryService->find($id);

        if (!$category) {
            return $this->responseService->error('Category not found', 404);
        }

        $this->categoryService->delete($id);
        return $this->responseService->success(null, 'Category deleted successfully');
    }

    public function restore(int $id): JsonResponse
    {
        $result = $this->categoryService->restore($id);

        if (!$result) {
            return $this->responseService->error('Category not found or cannot be restored', 404);
        }

        return $this->responseService->success(null, 'Category restored successfully');
    }
}
