<?php

namespace App\Notify\Channels;

use App\Notify\Contracts\Channel;
use App\Notify\Message;
use Illuminate\Support\Facades\Http;

/**
 * Discord incoming webhook. Setup:
 *   Channel settings → Integrations → Webhooks → New Webhook → copy URL
 *   notify:add-channel discord webhook_url=...
 */
class DiscordChannel implements Channel
{
    public function key(): string { return 'discord'; }

    public function requiredConfig(): array { return ['webhook_url']; }

    public function send(array $config, Message $message): array
    {
        // Discord embeds — colored sidebar matches severity.
        $color = hexdec(ltrim($message->color(), '#'));

        $payload = [
            'username'   => 'HostSeba AI Portal',
            'embeds' => [[
                'title'       => substr($message->title, 0, 256),
                'description' => substr($message->body, 0, 4000),
                'color'       => $color,
                'timestamp'   => now()->toIso8601String(),
                'footer'      => ['text' => 'HSAP · ' . strtoupper($message->severity)],
                'url'         => $message->url,
            ]],
        ];

        try {
            $resp = Http::timeout(8)->post($config['webhook_url'], $payload);
            if (! $resp->successful()) {
                return ['ok' => false, 'error' => 'HTTP ' . $resp->status() . ': ' . $resp->body()];
            }
            return ['ok' => true, 'response' => null];
        } catch (\Throwable $e) {
            return ['ok' => false, 'error' => $e->getMessage()];
        }
    }
}
