<?php

declare(strict_types=1);

function email_config(): array
{
    static $config = null;

    if ($config === null) {
        $path = __DIR__ . '/../config/email.php';
        $config = is_file($path) ? require $path : [];
    }

    return is_array($config) ? $config : [];
}

function email_is_enabled(): bool
{
    $config = email_config();

    return !empty($config['enabled'])
        && trim((string)($config['resend_api_key'] ?? '')) !== '';
}

function resend_send_email(array $payload): array
{
    if (!email_is_enabled()) {
        throw new RuntimeException('Email service is not configured.');
    }

    $config = email_config();
    $apiKey = trim((string)$config['resend_api_key']);

    $ch = curl_init('https://api.resend.com/emails');
    if ($ch === false) {
        throw new RuntimeException('Could not initialize email request.');
    }

    $body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($body === false) {
        throw new RuntimeException('Could not encode email payload.');
    }

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_TIMEOUT => 45,
    ]);

    $responseBody = curl_exec($ch);
    $statusCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($responseBody === false) {
        throw new RuntimeException('Email request failed: ' . ($curlError !== '' ? $curlError : 'unknown error'));
    }

    $decoded = json_decode($responseBody, true);
    if (!is_array($decoded)) {
        $decoded = ['raw' => $responseBody];
    }

    if ($statusCode < 200 || $statusCode >= 300) {
        $message = (string)($decoded['message'] ?? $decoded['error'] ?? 'Resend API error');
        throw new RuntimeException($message . ' (HTTP ' . $statusCode . ')');
    }

    return $decoded;
}

function resend_build_from(): string
{
    $config = email_config();
    $name = trim((string)($config['from_name'] ?? 'Karvi Partner'));
    $email = trim((string)($config['from_email'] ?? 'info@karvipro.de'));

    return $name . ' <' . $email . '>';
}

function resend_file_attachment(string $path, string $filename, ?string $contentId = null): ?array
{
    if (!is_file($path)) {
        return null;
    }

    $content = file_get_contents($path);
    if ($content === false) {
        return null;
    }

    $attachment = [
        'filename' => $filename,
        'content' => base64_encode($content),
    ];

    if ($contentId !== null && $contentId !== '') {
        $attachment['content_id'] = $contentId;
    }

    return $attachment;
}
