<?php

namespace fxratesapi\actions;

use Exception;
use traits\module_action_t;

class convert_rate_a
{
    use module_action_t;

    /**
     * @inheritDoc
     * @throws Exception If the module name is invalid
     */
    public function run(): void
    {
        self::set_module_name('FXRATESAPI');

        /** Add the action to the list of valid actions */
        // Convert rate action
        self::add_action(
            'CONVERT_RATE',
            'This action is when a currency conversion is requested',
            // Method to call
            self::class . '::convert_rate',
            [
                'from' => 'The currency to convert from (ISO 4217)',
                'to' => 'The currency to convert to (ISO 4217)',
                'data' => 'The data returned from the conversion (If any)',
                'status_code' => 'The status code of the action',
            ]
        );
    }

    /**
     * Convert rate action
     * @param string $from The currency to convert from (ISO 4217)
     * @param string $to The currency to convert to (ISO 4217)
     * @param array|object $data The data returned from the conversion (If any)
     * @param int $status_code The status code of the action
     * @throws Exception If the action name is invalid
     * @throws Exception If the action data is invalid
     * @throws Exception If the action status code is invalid
     * @throws Exception If the action is not valid
     */
    public function convert_rate(string $from, string $to, array|object $data = [], int $status_code = 0): void
    {
        self::set_action('CONVERT_RATE');
        // If the data is an object, convert it to an array
        if (is_object($data)) {
            $data = (array)$data;
        }
        // Validate the action data
        if (!is_array($data)) {
            throw new Exception('Action data is invalid');
        }
        // Validate the action status code
        self::set_data([
            'from' => $from,
            'to' => $to,
            'data' => $data,
        ]);
        self::set_status($status_code);
        // Add the action to the log
        self::add_action_log(
            self::get_action_name(),
            (int)self::get_status(),
        );
    }
}