<?php

namespace App\Services;

use App\Models\Notification;
use App\Models\User;
use App\Support\Channels\DatabaseNotificationChannel;
use App\Support\Channels\EmailNotificationChannel;
use App\Support\Channels\WhatsAppNotificationChannel;
use Illuminate\Database\Eloquent\Collection;

class NotificationService
{
    public function __construct(
        protected DatabaseNotificationChannel $databaseChannel,
        protected EmailNotificationChannel $emailChannel,
        protected WhatsAppNotificationChannel $whatsAppChannel
    ) {}

    public function notify(User $recipient, string $title, string $message, string $type = 'info', array $channels = ['database']): void
    {
        if (in_array('database', $channels)) {
            $this->databaseChannel->send($recipient, $title, $message, $type);
        }

        if (in_array('email', $channels)) {
            $this->emailChannel->send($recipient, $title, $message, $type);
        }

        if (in_array('whatsapp', $channels)) {
            $this->whatsAppChannel->send($recipient, $title, $message, $type);
        }
    }

    public function getUserUnreadNotifications(User $user): Collection
    {
        return Notification::where('user_id', $user->id)
            ->where('is_read', false)
            ->latest()
            ->get();
    }

    public function getUserAllNotifications(User $user, int $limit = 10): Collection
    {
        return Notification::where('user_id', $user->id)
            ->latest()
            ->limit($limit)
            ->get();
    }

    public function markAllAsRead(User $user): void
    {
        Notification::where('user_id', $user->id)
            ->where('is_read', false)
            ->update([
                'is_read' => true,
                'read_at' => now(),
            ]);
    }
}
