<?php

declare(strict_types=1);

namespace App\Services\Alerts;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class TeamsWebhookSender
{
    /**
     * @param  array<string, mixed>  $payload
     */
    public function send(string $webhookUrl, array $payload): void
    {
        $webhookUrl = trim($webhookUrl);

        if ($webhookUrl === '') {
            throw new RuntimeException('Teams webhook URL is not configured.');
        }

        $response = Http::timeout((int) config('tenantpilot.alerts.http_timeout_seconds', 10))
            ->asJson()
            ->post($webhookUrl, [
                'text' => $this->toTeamsTextPayload($payload),
            ]);

        if ($response->successful()) {
            return;
        }

        throw new RuntimeException(sprintf(
            'Teams delivery failed with HTTP status %d.',
            (int) $response->status(),
        ));
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    private function toTeamsTextPayload(array $payload): string
    {
        $title = trim((string) Arr::get($payload, 'title', 'Alert'));
        $body = trim((string) Arr::get($payload, 'body', 'A matching alert event was detected.'));

        if ($title === '') {
            $title = 'Alert';
        }

        if ($body === '') {
            return $title;
        }

        return $title."\n\n".$body;
    }
}
