<?php

namespace App\Classes\Modules\ServiceTypes\Services;


use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Http\Resources\CurrencyResource;
use App\Models\SegmentConstant;
use Illuminate\Database\Eloquent\Collection;

class FetchesServiceCurrenciesConfigurations
{

    /** @var FetchesCurrency */
    private $fetchesCurrency;

    /**
     * FetchesServiceCurrenciesConfigurations constructor.
     * @param FetchesCurrency $fetchesCurrency
     */
    public function __construct(FetchesCurrency $fetchesCurrency)
    {
        $this->fetchesCurrency = $fetchesCurrency;
    }

    public function execute(SegmentConstant $constants){

        $currencies = array_map(function($configuration) use($constants){

            $currency = $this->fetchesCurrency->execute(['id' => $configuration->id]);

            if(! $currency->exists()) return [];

            return json_decode(json_encode([
                'currency_object' => new CurrencyResource($currency),
                'id' => $configuration->id,
                'active' => true,
                'maximum_limit' => [
                    'type' => $configuration->max_limit->type,
                    'value' => number_format((float)$configuration->max_limit->value, 2, '.', ',')
                ],
                'minimum_limit' => [
                    'type' => $configuration->min_limit->type,
                    'value' => number_format((float)$configuration->min_limit->value, 2, '.', ',')
                ],
                'rates' => $constants->reference === SegmentConstants::SERVICE_TYPE ? $this->standardRates($currency->rates->where('service_id', $constants->detail->id)) : $configuration->rates
            ]));

        }, $constants->detail->currencies);

        return array_filter($currencies);

    }

    private function standardRates(Collection $rates){
        return $rates->map(function($rate){
            return [
                'payment_method' => PaymentMethodType::PAYMENT_METHODS_ID[$rate->payment_method_type],
                'selling' => [
                    'type' => 'rate',
                    'value' => $rate->selling
                ]
            ];
        });
    }

}