<?php

namespace EasyLinkAutomations\Auth\Platforms;

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

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

/**
 * Generic API Key authentication.
 *
 * Sends a token in a configurable header (defaults to Authorization: Bearer).
 */
final class GenericApiKeyAuth implements PlatformAuthInterface
{
    public static function getSlug(): string
    {
        return 'generic_api_key';
    }

    public static function getName(): string
    {
        return 'Custom API Key';
    }

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

    public static function getFields(): array
    {
        return [
            'api_key' => [
                'label'       => 'API Key',
                'type'        => 'text',
                'password'    => true,
                'required'    => true,
                'placeholder' => 'Enter your API key or token',
            ],
            'header_name' => [
                'label'       => 'Header Name',
                'type'        => 'text',
                'required'    => false,
                'placeholder' => 'Authorization',
                'default'     => 'Authorization',
            ],
            'header_prefix' => [
                'label'       => 'Header Value Prefix',
                'type'        => 'text',
                'required'    => false,
                'placeholder' => 'Bearer',
                'default'     => 'Bearer',
            ],
        ];
    }

    public static function getTestRequest(): ?array
    {
        return null;
    }

    public static function authenticate(array $credentials): array
    {
        $key        = trim((string) ($credentials['api_key'] ?? ''));
        $headerName = trim((string) ($credentials['header_name'] ?? 'Authorization'));
        $prefix     = trim((string) ($credentials['header_prefix'] ?? 'Bearer'));

        if ($headerName === '') {
            $headerName = 'Authorization';
        }

        $value = $prefix !== '' ? $prefix . ' ' . $key : $key;

        return [$headerName => $value];
    }

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