<?php

namespace App\Listeners;

use App\Services\OneSignalService;
use Illuminate\Notifications\Events\NotificationSent;
use Illuminate\Support\Facades\Log;

class SendOneSignalPush
{
    public function __construct(
        protected OneSignalService $oneSignal
    ) {}

    /**
     * database kanalıyla gönderilen bildirimlerden sonra OneSignal push gönder
     */
    public function handle(NotificationSent $event): void
    {
        if ($event->channel !== 'database') {
            return;
        }

        $notifiable = $event->notifiable;
        $notification = $event->notification;

        if (!method_exists($notification, 'toArray')) {
            return;
        }

        $data = $notification->toArray($notifiable);
        $type = $data['type'] ?? '';

        if (!str_starts_with($type, 'reservation_')) {
            return;
        }

        $title = $data['title'] ?? 'KaptanGo';
        $message = $data['message'] ?? '';

        $pushData = [
            'type' => $type,
            'reservation_id' => $data['reservation_id'] ?? null,
            'listing_id' => $data['listing_id'] ?? null,
            'action_url' => $data['action_url'] ?? null,
        ];

        $buttons = [];
        if ($type === 'reservation_created') {
            $buttons = [
                ['id' => 'approve', 'text' => 'Onayla'],
                ['id' => 'reject', 'text' => 'Reddet'],
            ];
        }

        $idempotencyKey = isset($notification->id) ? (string) $notification->id : null;

        try {
            $this->oneSignal->sendToUser(
                userId: $notifiable->id,
                title: $title,
                message: $message,
                data: $pushData,
                buttons: $buttons,
                idempotencyKey: $idempotencyKey,
            );
        } catch (\Throwable $e) {
            Log::error('SendOneSignalPush hatası', ['error' => $e->getMessage()]);
        }
    }
}
