<?php

namespace App\Observers;

use App\Models\User;
use App\Models\Deposit;
use App\Notifications\AdminActionNotification;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;
use Illuminate\Broadcasting\BroadcastException;

class NotifyAdminObserver
{
    protected function notify(string $title, string $message, Model $model, array $meta = []): void
    {
        $payload = $meta + [
            'model' => class_basename($model),
            'id'    => $model->getKey(),
        ];

        try {
            Notification::send(
                User::admins()->get(), // scopeAdmins ধরে নিচ্ছি
                new AdminActionNotification($title, $message, $payload)
            );
        } catch (BroadcastException $e) {
            Log::warning('Broadcast failed (Pusher): '.$e->getMessage(), [
                'payload' => $payload,
            ]);
        }
    }

    public function created(Model $model): void
    {
        if ($model instanceof Deposit) {
            $this->notify(
                'New Deposit',
                'A new deposit has been submitted.',
                $model,
                ['amount' => $model->amount]
            );
        }
    }
}
