<?php

namespace app\commands;

use Yii;
use yii\console\Controller;
use yii\httpclient\Client;

class CronController extends Controller
{
    /**
     * Make sure we're allowed to run cron actions in this container
     */
    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }

        if (!Yii::$app->params['allowCron']) {
            echo "Crons are forbidden in this container!\n";
            return false;
        }
        
        return true;
    }
    
    /**
     * Loads public keys for user token validation
     */
    public function actionLoadUserValidationKeys() {
        echo "Contacting User service for public keys...\n";
        // call the endpoint for the keys
        $url = Yii::$app->params['serviceUrls']['userApi'].'keys';
        echo "Calling $url...";

        $headers = [
            'Content-Type: application/json',
        ];

        $client = new Client();
        $response = $client->get($url)
            ->send();
        if ($response->isOk) {
            echo "Done!\n";
            $keys = $response->data['data'];
        } else {
            echo "HTTP error! ". $response->statusCode . ' - ' . json_encode($response)."\n";
            return;
        }

        // cache the keys locally in a format that they can be easily accessed
        $cacheKeys = [];
        foreach ($keys as $key) {
            $cacheKeys[$key['status']] = $key['pem'];
        }

        if (Yii::$app->cache->set('validationKeys.user', $cacheKeys)) {
            echo "Cached keys!\n";
            echo json_encode($cacheKeys);
        } else {
            echo "Error caching keys!\n";
        }
    }

    /**
     * Loads public keys for service token validation
     */
    public function actionLoadServiceValidationKeys() {
        echo "Contacting Service service for public keys...\n";
        // call the endpoint for the keys
        $url = Yii::$app->params['serviceUrls']['serviceApi'].'keys';
        echo "Calling $url...";

        $headers = [
            'Content-Type: application/json',
        ];

        $client = new Client();
        $response = $client->get($url)
            ->send();
        if ($response->isOk) {
            echo "Done!\n";
            $keys = $response->data['data'];
        } else {
            echo "HTTP error! ". $response->statusCode . ' - ' . json_encode($response)."\n";
            return;
        }

        // cache the keys locally in a format that they can be easily accessed
        $cacheKeys = [];
        foreach ($keys as $key) {
            $cacheKeys[$key['status']] = $key['pem'];
        }

        if (Yii::$app->cache->set('validationKeys.service', $cacheKeys)) {
            echo "Cached keys!\n";
            echo json_encode($cacheKeys);
        } else {
            echo "Error caching keys!\n";
        }
    }
}
