<?php

namespace EasyLinkAutomations\Auth\Platforms;

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

use EasyLinkAutomations\Auth\AuthType;
use EasyLinkAutomations\Auth\Contracts\PlatformAuthInterface;

/**
 * Notion API token authentication.
 *
 * Uses an internal connection's installation access token as a Bearer token.
 * Also injects the required Notion-Version header.
 * Test endpoint: https://api.notion.com/v1/users/me
 */
final class NotionAuth implements PlatformAuthInterface
{
    public static function getSlug(): string
    {
        return 'notion';
    }

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

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

    public static function getFields(): array
    {
        return [
            'api_key' => [
                'label'       => 'Installation Access Token',
                'type'        => 'text',
                'password'    => true,
                'required'    => true,
                'placeholder' => 'ntn_xxxxxxxxxxxxxxxx',
                'description' => 'Copy the token from your internal connection’s Configuration tab, then grant that connection access to the pages and databases used by your automations.',
            ],
        ];
    }

    public static function getTestRequest(): ?array
    {
        return [
            'url'    => 'https://api.notion.com/v1/users/me',
            'method' => 'GET',
        ];
    }

    public static function authenticate(array $credentials): array
    {
        return [
            'Authorization'  => 'Bearer ' . ($credentials['api_key'] ?? ''),
            'Notion-Version' => '2022-06-28',
        ];
    }

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