<?php

namespace EasyLinkAutomations\Auth\Platforms;

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

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

/**
 * Generic HTTP Basic authentication.
 *
 * Sends username and password as a base64-encoded Authorization header.
 */
final class GenericBasicAuth implements PlatformAuthInterface
{
    public static function getSlug(): string
    {
        return 'generic_basic_auth';
    }

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

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

    public static function getFields(): array
    {
        return [
            'username' => [
                'label'       => 'Username',
                'type'        => 'text',
                'required'    => true,
                'placeholder' => 'Enter username',
            ],
            'password' => [
                'label'       => 'Password',
                'type'        => 'text',
                'password'    => true,
                'required'    => true,
                'placeholder' => 'Enter password',
            ],
        ];
    }

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

    public static function authenticate(array $credentials): array
    {
        $username = $credentials['username'] ?? '';
        $password = $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(),
        ];
    }
}
