<?php

namespace App\Http\Controllers\Apis;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

use App\Services\Banxico\BanxicoService;

class CurrencyController extends Controller
{
  //* Connection Functions
    public function getRate($code, BanxicoService $banxico_service){
      //* Get supported currencies by Banxico
        $currencies = config('constants.banxico_currencies');

      //* Parse & Validate provided code
        $code = trim(strtoupper($code)); // Clean code

        // Is the currency supported by banxico?
        if(!isset($currencies[$code])){
            return response()->json([
                'status' => 'not_supported',
                'message' => 'La moneda no esta disponible en el catalogo de Banxico'
            ], 200);
        }

      //* Fetch Banxico
        $cache_key = "banxico_rate_{$code}"; // Cache code

        // Retrieve currency parity and cache it
        $rate = Cache::remember($cache_key, 600, function() use($currencies, $code, $banxico_service){
            $series_id= $currencies[$code]['id']; // Extract banxico currency UUID

            $data = $banxico_service->getSeriesData($series_id); // Request for parity
            $rate= $data['bmx']['series'][0]['datos'][0]['dato'] ?? null;

            if( is_numeric($rate) ) return (float) $rate;
            return null;
        });

        // Only return success queries
        if ($rate)
            return response()->json([ 'status' => 'ok', 'rate' => $rate ]);

        return response()->json([
            'status' => 'not_supported',
            'message' => 'Banxico devolvió texto en el campo dato... '
        ], 200);
    }
}
