<?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\Facebook;

use function YOOtheme\app;
use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use ZOOlanders\YOOessentials\HttpClientInterface;
use ZOOlanders\YOOessentials\Api\Facebook\FacebookBaseApi;

class FacebookAuthDriverController
{
    /**
     * @var string
     */
    public const PRE_SAVE_ENDPOINT = 'yooessentials/auth/facebook';

    public function presave(Request $request, Response $response, HttpClientInterface $client)
    {
        $form = $request->getParam('auth', []);
        $accessToken = $form['accessToken'] ?? null;

        if (!$accessToken) {
            return $response->withJson('Access Token must be specified.', 400);
        }

        try {
            /** @var FacebookBaseApi $api */
            $api = app(FacebookBaseApi::class);
            $result = $api->withAccessToken($accessToken)->me();

            $form['fullName'] = $result['name'] ?? $form['fullName'] ?? null;
            $form['scopes'] = $result['scopes'] ?? $form['scopes'] ?? [];
            $form['userId'] = $result['id'] ?? $form['id'] ?? 'me';
            $form['expiresAt'] = $result['data_access_expires_at'] ?? $form['expiresAt'] ?? null;
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        return $response->withJson($form);
    }
}
