<?php

namespace App\Services;

use App\Models\UserNotification;

class UserNotificationService
{
    public function __construct(private readonly NotificationChannelService $notificationChannelService)
    {
    }

    /**
     * @param array<string, mixed> $meta
     */
    public function create(int $userId, string $type, string $title, string $message, ?string $link = null, array $meta = []): UserNotification
    {
        $notification = UserNotification::query()->create([
            'user_id' => $userId,
            'type' => $type,
            'title' => $title,
            'message' => $message,
            'link' => $link,
            'meta' => $meta === [] ? null : $meta,
        ]);

        try {
            $user = $notification->user()->first();
            if ($user) {
                $this->notificationChannelService->sendToUserChannels($user, $title, $message, $link, ['email', 'whatsapp', 'sms']);
            }
        } catch (\Throwable) {
            // Keep in-app notification path resilient.
        }

        return $notification;
    }
}

