<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Auth\Driver\Mailchimp;

use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use YOOtheme\Str;
use ZOOlanders\YOOessentials\Api\Mailchimp\MailchimpApi;

class MailchimpController
{
    /**
     * @var string
     */
    public const PRE_OAUTH_SAVE_ENDPOINT = 'yooessentials/auth/mailchimp/oauth';
    public const PRE_APIKEY_SAVE_ENDPOINT = 'yooessentials/auth/mailchimp/apikey';

    public function presaveOauth(Request $request, Response $response, MailchimpApi $api)
    {
        $auth = $request->getParam('auth');
        $accessToken = $auth['accessToken'] ?? null;

        try {
            if (!$accessToken) {
                throw new \Exception('Missing Access Token or no access has been granted.');
            }

            $metadata = $api->getOauthMetadata($accessToken);

            $auth['dc'] = $metadata['dc'] ?? '';
            $auth['account'] = $metadata['accountname'] ?? '';

            if (!$auth['dc']) {
                throw new \Exception('Error at retrieving the user Data Center prefix.');
            }
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        return $response->withJson($auth, 200);
    }

    public function presaveApikey(Request $request, Response $response, MailchimpApi $api)
    {
        $auth = $request->getParam('auth');
        $key = $auth['key'] ?? null;

        try {
            if (!$key) {
                throw new \Exception('Missing API key.');
            }

            if (!Str::contains($key, '-')) {
                throw new \Exception('Invalid Key format.');
            }

            $metadata = $api->withApiKey($key)->getAccountMetadata();

            $auth['account'] = $metadata['account_name'] ?? '';
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        return $response->withJson($auth, 200);
    }
}
