<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Schema;

/**
 * Shared helpers for location-inventory mode detection and ledger created_by resolution.
 */
trait LocationInventoryModeConcern
{
    public function useLocationInventory(): bool
    {
        if (!Schema::hasTable('inventory_balances') || !Schema::hasTable('stock_ledger')) {
            return false;
        }

        // Honor inventory_location_mode when present; missing/empty => location mode (tables exist).
        try {
            $mode = Setting::get('inventory_location_mode');
        } catch (\Throwable $e) {
            $mode = null;
        }
        if ($mode === null || $mode === '') {
            return true;
        }
        $normalized = strtolower(trim((string) $mode));
        if (in_array($normalized, ['legacy', 'false', '0', 'off', 'disabled'], true)) {
            return false;
        }
        if (in_array($normalized, ['location', 'locations', 'true', '1', 'on', 'enabled'], true)) {
            return true;
        }

        return true;
    }

    /**
     * Resolve created_by for ledger rows -- never silently fake user id 1.
     */
    protected function resolveCreatedBy(?int $createdBy = null): ?int
    {
        $id = $createdBy ?? auth()->id();
        return $id ? (int) $id : null;
    }

    protected function requireCreatedBy(?int $createdBy = null): int
    {
        $id = $this->resolveCreatedBy($createdBy);
        if (!$id) {
            throw new StockException('Authenticated user is required for inventory ledger writes.');
        }

        return $id;
    }
}
