<?php

namespace App\Services;

use GuzzleHttp\Client as GuzzleClient;
use Google\Client;
use RuntimeException;

class GoogleClientFactory
{
    public function make(): Client
    {
        return $this->makeUserOAuth();
    }

    public function hasOAuthConfig(): bool
    {
        return is_string(config('google.oauth_client_id'))
            && config('google.oauth_client_id') !== ''
            && is_string(config('google.oauth_client_secret'))
            && config('google.oauth_client_secret') !== '';
    }

    public function hasUserOAuth(): bool
    {
        return $this->hasOAuthConfig() && GoogleOAuthSession::isLoggedIn();
    }

    public function makeUserOAuth(): Client
    {
        if (! $this->hasOAuthConfig()) {
            throw new RuntimeException('Thiếu GOOGLE_OAUTH_CLIENT_ID / SECRET trong .env');
        }

        if (! GoogleOAuthSession::isLoggedIn()) {
            throw new RuntimeException('Chưa đăng nhập Google. Vui lòng đăng nhập trước khi sử dụng.');
        }

        $client = new Client;
        $client->setApplicationName(config('app.name', 'Check Google Sheet'));
        $client->setClientId(config('google.oauth_client_id'));
        $client->setClientSecret(config('google.oauth_client_secret'));
        $client->setScopes(config('google.oauth_scopes', []));
        $client->setAccessType('offline');
        $client->setHttpClient(new GuzzleClient([
            'timeout' => (float) config('google.http_timeout_seconds', 20),
            'connect_timeout' => (float) config('google.http_connect_timeout_seconds', 10),
        ]));
        $client->fetchAccessTokenWithRefreshToken(GoogleOAuthSession::refreshToken());

        return $client;
    }

    public function makeOAuthForAuth(): Client
    {
        $clientId = config('google.oauth_client_id');
        $clientSecret = config('google.oauth_client_secret');
        $redirectUri = config('google.oauth_redirect_uri');

        if (! is_string($clientId) || ! is_string($clientSecret) || ! is_string($redirectUri)) {
            throw new RuntimeException('Thiếu GOOGLE_OAUTH_CLIENT_ID / SECRET / REDIRECT_URI trong .env');
        }

        $client = new Client;
        $client->setApplicationName(config('app.name', 'Check Google Sheet'));
        $client->setClientId($clientId);
        $client->setClientSecret($clientSecret);
        $client->setRedirectUri($redirectUri);
        $client->setScopes(config('google.oauth_scopes', []));
        $client->setAccessType('offline');
        $client->setPrompt('consent');
        $client->setHttpClient(new GuzzleClient([
            'timeout' => (float) config('google.http_timeout_seconds', 20),
            'connect_timeout' => (float) config('google.http_connect_timeout_seconds', 10),
        ]));

        return $client;
    }
}
