<?php

namespace EasyLinkAutomations\Auth\Platforms;

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

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

/**
 * Mailchimp OAuth2 authentication.
 *
 * Uses Mailchimp OAuth2 with Marketing API access. After obtaining the token,
 * a metadata call determines the correct API datacenter endpoint.
 * The metadata endpoint expects the OAuth authorization scheme.
 */
final class MailchimpAuth implements OAuth2PlatformAuthInterface
{
    public static function getSlug(): string
    {
        return 'mailchimp';
    }

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

    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 Mailchimp OAuth App Client ID',
            ],
            'client_secret' => [
                'label'       => 'Client Secret',
                'type'        => 'text',
                'password'    => true,
                'required'    => true,
                'placeholder' => 'Your Mailchimp OAuth App Client Secret',
            ],
        ];
    }

    public static function getOAuth2Config(): array
    {
        return [
            'auth_url'  => 'https://login.mailchimp.com/oauth2/authorize',
            'token_url' => 'https://login.mailchimp.com/oauth2/token',
            'scope'     => '',
        ];
    }

    public static function getTestRequest(): ?array
    {
        return [
            'url'    => 'https://login.mailchimp.com/oauth2/metadata',
            'method' => 'GET',
        ];
    }

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

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

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