<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Stock\AdjustStockRequest;
use App\Http\Resources\StockLevelResource;
use App\Models\Product;
use App\Models\StockLevel;
use App\Services\InventoryService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class StockController extends ApiController
{
    public function __construct(private readonly InventoryService $inventoryService)
    {
    }

    public function index(Request $request): AnonymousResourceCollection
    {
        $branchId = $this->currentBranchId($request);
        $search = $request->string('search')->toString();

        $stock = StockLevel::query()
            ->with(['product', 'variant'])
            ->where('branch_id', $branchId)
            ->when($search !== '', function ($query) use ($search) {
                $query->whereHas('product', function ($productQuery) use ($search) {
                    $productQuery->where('name', 'like', "%{$search}%")
                        ->orWhere('sku', 'like', "%{$search}%")
                        ->orWhere('barcode', 'like', "%{$search}%");
                });
            })
            ->orderByDesc('updated_at')
            ->paginate((int) $request->integer('per_page', 15));

        return StockLevelResource::collection($stock);
    }

    public function adjust(AdjustStockRequest $request): StockLevelResource
    {
        $product = Product::findOrFail($request->integer('product_id'));
        $this->ensureCompanyScoped($product, $this->currentCompanyId($request));

        $stock = $this->inventoryService->adjust(
            user: $this->currentUser($request),
            branchId: $this->currentBranchId($request),
            product: $product,
            variantId: $request->integer('variant_id') ?: null,
            quantityDelta: (float) $request->input('quantity'),
            type: $request->string('type')->toString(),
            unitCost: $request->filled('unit_cost') ? (float) $request->input('unit_cost') : null,
            batchId: $request->integer('batch_id') ?: null,
            notes: $request->input('notes'),
            deviceId: $request->input('device_id'),
        );

        return new StockLevelResource($stock->load(['product', 'variant']));
    }
}
