<?php

namespace EasyLinkAutomations\Auth\Platforms;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Auth\AuthType;
use EasyLinkAutomations\Auth\Contracts\OAuth2PlatformAuthInterface;

/**
 * Google Sheets OAuth2 authentication.
 *
 * Uses Google OAuth2 with Sheets and Drive scopes. The access token is
 * sent as a Bearer token in the Authorization header.
 */
final class GoogleSheetsAuth implements OAuth2PlatformAuthInterface
{
    public static function getSlug(): string
    {
        return 'google_sheets';
    }

    public static function getName(): string
    {
        return 'Google Sheets';
    }

    public static function getAuthType(): string
    {
        return AuthType::OAUTH2;
    }

    public static function getFields(): array
    {
        return [
            'client_id' => [
                'label'       => 'Client ID',
                'type'        => 'text',
                'required'    => true,
                'placeholder' => 'Your Google Cloud Client ID',
            ],
            'client_secret' => [
                'label'       => 'Client Secret',
                'type'        => 'text',
                'password'    => true,
                'required'    => true,
                'placeholder' => 'Your Google Cloud Client Secret',
            ],
        ];
    }

    public static function getOAuth2Config(): array
    {
        return [
            'auth_url'    => 'https://accounts.google.com/o/oauth2/v2/auth',
            'token_url'   => 'https://oauth2.googleapis.com/token',
            'scope'       => 'https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.readonly',
            'auth_params' => [
                'access_type' => 'offline',
                'prompt'      => 'consent',
            ],
        ];
    }

    public static function getTestRequest(): ?array
    {
        return [
            'url'    => 'https://www.googleapis.com/drive/v3/about?fields=user',
            'method' => 'GET',
        ];
    }

    public static function authenticate(array $credentials): array
    {
        $token = $credentials['access_token'] ?? '';

        return ['Authorization' => 'Bearer ' . $token];
    }

    public static function toArray(): array
    {
        return [
            'slug'          => static::getSlug(),
            'name'          => static::getName(),
            'auth_type'     => static::getAuthType(),
            'fields'        => static::getFields(),
            'oauth2_config' => static::getOAuth2Config(),
        ];
    }
}
