<?php

namespace App\Services;

use App\Mail\LineupUserNotificationMail;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;

class EmailNotificationService
{
    public function notifyUserById(
        int $userId,
        string $title,
        string $body,
        array $payload = [],
    ): void {
        $user = User::query()
            ->select('id', 'role', 'email', 'email_notifications_enabled')
            ->whereKey($userId)
            ->first();

        if (!$user) {
            return;
        }

        $this->notifyUser($user, $title, $body, $payload);
    }

    public function notifyUser(
        User $user,
        string $title,
        string $body,
        array $payload = [],
    ): void {
        if (!in_array($user->role, ['client', 'liner'], true)) {
            return;
        }

        if ($user->email_notifications_enabled === false) {
            return;
        }

        $email = trim((string) $user->email);
        if ($email === '') {
            return;
        }

        try {
            Mail::to($email)->send(new LineupUserNotificationMail($title, $body, $payload));
        } catch (Throwable $exception) {
            Log::warning('lineup.notifications.mail.failed', [
                'user_id' => $user->id,
                'email' => $email,
                'message' => $exception->getMessage(),
            ]);
        }
    }
}
