<?php

namespace FleekDash\API;

use FleekDash\Core\AuthMiddleware;
use Google_Client;
use Google_Service_Gmail;
use Throwable;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

class Gmail
{
    private Google_Client $client;

    private string $redirectUri;

    public function __construct()
    {
        $this->client = new Google_Client();
        $this->redirectUri = \site_url('/wp-json/fleekdash/v1/gmail/callback');

        // Set up Google Client
        $this->client->setClientId(\get_option('fleekdash_gmail_client_id'));
        $this->client->setClientSecret(\get_option('fleekdash_gmail_client_secret'));
        $this->client->setRedirectUri($this->redirectUri);
        $this->client->addScope(Google_Service_Gmail::GMAIL_READONLY);
        $this->client->setAccessType('offline');
        $this->client->setPrompt('consent');
    }

    /**
     * Initialize OAuth flow
     */
    public function initAuth(): WP_REST_Response|WP_Error
    {
        try {
            $auth_url = $this->client->createAuthUrl();

            return new WP_REST_Response([
                'status' => 'success',
                'authUrl' => $auth_url,
            ], 200);
        } catch (Throwable $e) {
            return new WP_Error(
                'gmail_auth_error',
                $e->getMessage(),
                ['status' => 500],
            );
        }
    }

    /**
     * Handle OAuth callback
     */
    public function handleCallback(WP_REST_Request $request): void
    {
        try {
            $code = $request->get_param('code');
            if (empty($code)) {
                throw new GmailOAuthException('Authorization code is missing');
            }

            // Exchange authorization code for access token
            $token = $this->client->fetchAccessTokenWithAuthCode($code);

            if (isset($token['error'])) {
                throw new GmailOAuthException($token['error_description'] ?? 'Failed to get access token');
            }

            // Store the token in WordPress user meta
            $user_id = \get_current_user_id();
            \update_user_meta($user_id, 'fleekdash_gmail_token', $token);

            // Redirect to success page
            wp_redirect(\admin_url('admin.php?page=fleekdash-accounts&connection=gmail&status=success'));
            exit;
        } catch (Throwable $e) {
            wp_redirect(\admin_url('admin.php?page=fleekdash-accounts&connection=gmail&status=error&message=' . rawurlencode($e->getMessage())));
            exit;
        }
    }

    /**
     * Register REST API routes
     */
    public function registerRoutes(): void
    {
        \register_rest_route('fleekdash/v1', '/gmail/auth', [
            'methods' => 'POST',
            'callback' => [$this, 'initAuth'],
            'permission_callback' => function () {
                return \current_user_can('manage_options');
            },
        ]);

        \register_rest_route('fleekdash/v1', '/gmail/callback', [
            'methods' => 'GET',
            'callback' => [$this, 'handleCallback'],
            'permission_callback' => [AuthMiddleware::class, 'createAuthenticatedPermissionCallback'],
        ]);
    }
}
