<?php

namespace Modules\Inventory\Services;

use App\Models\ActivityLogModel;
use App\Models\ProductModel;

class ReorderLevelService
{
    protected ProductModel $products;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->products = new ProductModel();
        $this->activity = new ActivityLogModel();
    }

    /**
     * @param list<array{product_id: int|string, reorder_level: float|string}> $levels
     */
    public function updateLevels(array $levels, ?int $actingUserId): array
    {
        if ($levels === []) {
            return ['success' => false, 'errors' => ['levels' => 'No reorder levels provided.']];
        }

        $updated = 0;

        foreach ($levels as $level) {
            $productId = (int) ($level['product_id'] ?? 0);
            if ($productId <= 0) {
                continue;
            }

            $product = $this->products->find($productId);
            if (! $product) {
                continue;
            }

            $reorderLevel = (float) ($level['reorder_level'] ?? 0);

            if (! $this->products->update($productId, [
                'reorder_level' => $reorderLevel,
                'updated_by'    => $actingUserId,
            ])) {
                return ['success' => false, 'errors' => $this->products->errors()];
            }

            $updated++;
        }

        $this->activity->log(
            'reorder_levels',
            'updated',
            $actingUserId,
            "Updated reorder levels for {$updated} product(s)"
        );

        return ['success' => true, 'updated' => $updated];
    }
}
