<?php

namespace App\Services;

use App\Models\Notification;
use App\Models\User;
use App\Models\Vendor;
use Illuminate\Support\Facades\Auth;

class NotificationService
{
    public function broadcast(array $data): Notification
    {
        $notification = Notification::create([
            'title' => $data['title'],
            'body' => $data['body'],
            'channel' => $data['channel'] ?? 'in_app',
            'target' => $data['target'] ?? 'all',
            'target_ids' => $data['target_ids'] ?? null,
            'sent_by' => Auth::guard('admin')->id(),
            'sent_at' => now(),
        ]);

        // Count recipients for logging
        $count = match ($data['target']) {
            'customers' => User::count(),
            'vendors' => Vendor::count(),
            'specific' => count($data['target_ids'] ?? []),
            default => User::count() + Vendor::count(),
        };

        $notification->update(['sent_count' => $count]);

        return $notification;
    }
}
