<?php

namespace App\Notify\Channels;

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

/**
 * Pushover ($5 one-time per platform). Sends instant push to iOS/Android
 * with priority + sound options. Setup:
 *   1. pushover.net → register → grab user key
 *   2. Create an application → grab app token
 *   3. Install the Pushover app on your phone, sign in
 *   4. notify:add-channel pushover token=... user=... [device=...]
 */
class PushoverChannel implements Channel
{
    public function key(): string { return 'pushover'; }

    public function requiredConfig(): array { return ['token', 'user']; }

    public function send(array $config, Message $message): array
    {
        // Map our severity to Pushover priority. Critical = emergency
        // (priority 2 — repeats until acknowledged).
        $priority = match ($message->severity) {
            'critical' => 2,
            'high'     => 1,
            'medium', 'low' => 0,
            default    => -1,
        };

        $payload = array_filter([
            'token'    => $config['token'],
            'user'     => $config['user'],
            'title'    => substr($message->title, 0, 250),
            'message'  => substr($message->body, 0, 1024),
            'priority' => $priority,
            'url'      => $message->url,
            'url_title'=> $message->url ? 'Open in portal' : null,
            'device'   => $config['device'] ?? null,
            // Emergency requires retry + expire fields.
            'retry'    => $priority === 2 ? 60 : null,
            'expire'   => $priority === 2 ? 1800 : null,
        ], fn ($v) => $v !== null);

        try {
            $resp = Http::timeout(8)->asForm()->post('https://api.pushover.net/1/messages.json', $payload);
            if (! $resp->successful()) {
                return ['ok' => false, 'error' => 'Pushover HTTP ' . $resp->status() . ': ' . $resp->body()];
            }
            return ['ok' => true, 'response' => $resp->json()];
        } catch (\Throwable $e) {
            return ['ok' => false, 'error' => $e->getMessage()];
        }
    }
}
