<?php

namespace App\Http\Controllers\Api\Inventory;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Inventory\InventoryMovementBulkDeleteRequest;
use App\Http\Requests\Inventory\InventoryMovementIndexRequest;
use App\Http\Requests\Inventory\InventoryMovementStoreRequest;
use App\Http\Requests\Inventory\InventoryMovementUpdateRequest;
use App\Http\Resources\Inventory\InventoryMovementResource;
use App\Services\Inventory\InventoryMovementService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class InventoryMovementController extends BaseApiController
{
    public function __construct(private InventoryMovementService $movements)
    {
        parent::__construct();
    }

    public function index(InventoryMovementIndexRequest $request): JsonResponse
    {
        $rows = $this->movements->list($request->validated());

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

    public function store(InventoryMovementStoreRequest $request): JsonResponse
    {
        $actor = $this->authenticatedUserIdOrUnauthorized();
        if ($actor instanceof JsonResponse) {
            return $actor;
        }

        $result = $this->movements->create($request->validated(), $actor);
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to create movement.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->respondCreated();
    }

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

        return $this->success();
    }

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

        return $this->respondDeleted();
    }

    public function bulkDelete(InventoryMovementBulkDeleteRequest $request): JsonResponse
    {
        $result = $this->movements->bulkDelete($request->validated()['ids']);
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Bulk delete failed.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success($result);
    }

    /**
     * @return int|JsonResponse
     */
    private function authenticatedUserIdOrUnauthorized(): int|JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return $this->error('Unauthorized.', Response::HTTP_UNAUTHORIZED);
        }

        return $userId;
    }
}
