<?php

namespace common\components;

use common\helpers\Password;
use GuzzleHttp\Client;
use domain\Producer\Producer\Producer;
use yii\base\ErrorException;

class AlwaysdataClient
{
    public function initRedirections(Producer $producer)
    {
        $this->createProducerSiteShortUrlRedirection($producer);
        $this->createProducerEmailRedirection($producer);
    }

    public function createProducerEmailRedirection(Producer $producer)
    {
        return $this->post('mailbox',[
            'domain' => \Yii::$app->parameterBag->get('alwaysdataDomainId'),
            'name' => $producer->slug,
            'password' => Password::generate(13),
            'redirect_enabled' => true,
            'redirect_to' => $producer->contact_email
        ]);
    }

    public function createProducerSiteShortUrlRedirection(Producer $producer)
    {
        return $this->post('site', [
            'addresses' => [$producer->slug.'.souke.fr'],
            'type' => 'redirect',
            'url' => 'https://producteurs.souke.fr/'.$producer->slug,
            'redirect_type' => 'PERMANENT',
            'annotation' => 'Souke / '.$producer->name
        ]);
    }

    private function post(string $resource, array $data)
    {
        $client = $this->getClient($resource);

        return $client->request('POST', '', [
            'body' => json_encode($data)
        ]);
    }

    private function getClient(string $resource)
    {
        $this->checkConfiguration();

        return new Client([
            'base_uri' => \Yii::$app->parameterBag->get('alwaysdataApiUrl').$resource.'/',
            'auth' => [\Yii::$app->parameterBag->get('alwaysdataApiKey').' account='.\Yii::$app->parameterBag->get('alwaysdataAccount'), ''],
        ]);
    }

    private function checkConfiguration()
    {
        if(!\Yii::$app->parameterBag->has('alwaysdataApiUrl')
            || !\Yii::$app->parameterBag->has('alwaysdataAccount')
            || !\Yii::$app->parameterBag->has('alwaysdataApiKey')
            || !\Yii::$app->parameterBag->has('alwaysdataDomainId')) {

            throw new ErrorException('Configuration API Alwaysdata absente ou incomplète dans params-local.php');
        }
    }
}