<?php

namespace EasyLinkAutomations\Auth\Platforms;

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

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

/**
 * rapidmail API v3 HTTP Basic authentication.
 *
 * rapidmail issues a dedicated API user and password per account, created
 * under Settings → API in the rapidmail dashboard. These are separate from
 * the dashboard login and are sent as standard HTTP Basic credentials.
 *
 * Test endpoint: https://apiv3.emailsys.net/v1/recipientlists
 */
final class RapidmailAuth implements PlatformAuthInterface
{
    /**
     * Base URL for the rapidmail API v3, including the version segment.
     */
    public const API_BASE = 'https://apiv3.emailsys.net/v1';

    public static function getSlug(): string
    {
        return 'rapidmail';
    }

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

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

    public static function getFields(): array
    {
        return [
            'username' => [
                'label'       => 'API User',
                'type'        => 'text',
                'required'    => true,
                'placeholder' => 'Your rapidmail API username',
                'description' => 'Create an API user under Settings → API in rapidmail. This is not your dashboard login.',
            ],
            'password' => [
                'label'       => 'API Password',
                'type'        => 'text',
                'password'    => true,
                'required'    => true,
                'placeholder' => 'Your rapidmail API password',
                'description' => 'Shown once when the API user is created. Generate a new one if you no longer have it.',
            ],
        ];
    }

    public static function getTestRequest(): ?array
    {
        return [
            'url'    => self::API_BASE . '/recipientlists',
            'method' => 'GET',
        ];
    }

    public static function authenticate(array $credentials): array
    {
        $username = trim((string) ($credentials['username'] ?? ''));
        $password = (string) ($credentials['password'] ?? '');

        return [
            'Authorization' => 'Basic ' . base64_encode($username . ':' . $password),
        ];
    }

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