<?php

declare(strict_types=1);

namespace PpPhp\Core\Deploy;

/**
 * Builds the right transport for a saved connection profile.
 *
 * A profile is the array persisted by the Deploy module:
 *   [
 *     'name'           => 'Production',
 *     'protocol'       => 'ftp' | 'ftps' | 'sftp',
 *     'host'           => 'ftp.example.com',
 *     'port'           => 21,
 *     'user'           => '...',
 *     'pass'           => '...',
 *     'remotePath'     => '/public_html/app',
 *     'passive'        => true,          // FTP/FTPS only
 *     'privateKeyFile' => '/path/id_rsa' // SFTP key auth (optional)
 *     'privateKeyPass' => '...',
 *   ]
 */
class TransportFactory
{
    public static function make(array $profile): TransportInterface
    {
        $protocol = strtolower((string) ($profile['protocol'] ?? 'ftp'));

        return match ($protocol) {
            'sftp' => new SftpTransport([
                'host'           => $profile['host'] ?? '',
                'port'           => (int) ($profile['port'] ?? 22) ?: 22,
                'user'           => $profile['user'] ?? '',
                'pass'           => $profile['pass'] ?? '',
                'privateKeyFile' => $profile['privateKeyFile'] ?? '',
                'privateKeyPass' => $profile['privateKeyPass'] ?? '',
                'timeout'        => (int) ($profile['timeout'] ?? 20) ?: 20,
            ]),
            'ftp', 'ftps' => new FtpTransport([
                'host'    => $profile['host'] ?? '',
                'port'    => (int) ($profile['port'] ?? 21) ?: 21,
                'user'    => $profile['user'] ?? '',
                'pass'    => $profile['pass'] ?? '',
                'secure'  => $protocol === 'ftps',
                'passive' => $profile['passive'] ?? true,
                'timeout' => (int) ($profile['timeout'] ?? 20) ?: 20,
            ]),
            default => throw new TransportException("Unknown server protocol: {$protocol}"),
        };
    }

    /** Default port for a protocol, used by the UI. */
    public static function defaultPort(string $protocol): int
    {
        return strtolower($protocol) === 'sftp' ? 22 : 21;
    }
}
