<?php

namespace App\Services;

use App\Enums\FlightNotificationType;
use App\Models\Notification;
use App\Models\User;
use App\Models\UserFlight;

class FollowerNotificationService
{
    /**
     * Notify a user's followers about something that happened to one of their flights.
     */
    public function notifyFlightEvent(UserFlight $flight, FlightNotificationType $type): void
    {
        $this->notify(
            user: $flight->user,
            settingKey: $type->settingKey(),
            title: $type->title($flight->user),
            body: $type->body($flight),
            url: $type->url($flight),
        );
    }

    /**
     * Generic entry point for any future "notify all followers about X" need
     * that isn't tied to a flight event.
     */
    public function notify(User $user, string $settingKey, string $title, string $body, string $url): void
    {
        $user->followers()
            ->get()
            ->filter(fn (User $follower) => $follower->getSetting($settingKey))
            ->each(fn (User $follower) => Notification::create([
                'user_id' => $follower->id,
                'title'   => $title,
                'body'    => $body,
                'url'     => $url,
            ]));
    }
}
