<?php

namespace routes;

use classes\authentication;
use classes\fxratesapi;
use classes\response;
use classes\router;
use classes\virkdata;
use objects\currency_conversion_rates_o;
use objects\logs_o;
use traits\route_t;

class moduleVirkDataRoute
{
    use route_t;

    public function run(): void
    {
        global /** @var response $response */
        /** @var router $router */
        $router, $response;


        /** Modules > VirkData > search > GET */
        $this->get('/modules/virkdata/search', function () {
            global $response;
            self::requirePermission('modules_virkdata_search');
            $user = (new authentication())->get_user();
            if ($user) {
                self::requireParameters(['search']);
                self::requireType('search', self::type_string());
                self::requireMinLength('search', 3);
                self::requireMaxLength('search', 100);
                (new logs_o())->add('modules_virkdata', 'global', 1, $user->id, 'MODULES_VIRKDATA', 'User accessed searched for a company');
                $result = (new virkdata())->getCompanyInformation(
                    self::getParameter('search'),
                    '',
                    []
                );
                // Check if the result is an error
                if (isset($result->message)) {
                    (new logs_o())->add('modules_virkdata', 'global', 1, $user->id, 'MODULES_VIRKDATA', 'User accessed the conversion rate and got an error');
                    $response->error($result->message, 400);
                }
                $res = $result->asArray();
                // Response
                $response->success($res);
            } else {
                (new logs_o())->add('modules_virkdata', 'global', 1, 0, 'MODULES_VIRKDATA', 'User accessed the conversion rate without being logged in');
                $response->error('Invalid session', 400);
            }
        },
            [
                'modules_virkdata_rate' => 'Update conversion rates using the VIRKDATA',
            ]
        );

    }
}