<?php

declare(strict_types=1);

namespace Apexl\Io\Services;

use Apexl\Io\Interfaces\HasCurrencyCastsInterface;
use Apexl\Io\System;
use Money\Money;

final readonly class MoneyFactory
{
    public function __construct(private CurrencyFactory $currencyFactory) {}

    public function money(HasCurrencyCastsInterface $hasCurrencyCasts, string|int|float $numericValue, string $field): Money
    {
        $numericValue = $this->value($hasCurrencyCasts, $numericValue, $field);

        return System::makeRegisteredService(Money::class, [
            'amount' => $numericValue,
            'currency' => $this->currencyFactory->currency($hasCurrencyCasts->currencyCode()),
        ]);
    }

    private function value(HasCurrencyCastsInterface $hasCurrencyCasts, string|int|float $value, string $field): int
    {
        $numericValue = $this->ensureNumericValue($value);

        $multiplier = $hasCurrencyCasts->currencyMultiplier($field);

        return (int) ($numericValue * $multiplier);
    }

    private function ensureNumericValue(float|int|string $value): int|float
    {
        if (is_string($value)) {
            if (str_contains($value, '.')) {
                return (float) $value;
            }

            return (int) $value;
        }
        return $value;

    }
}