<?php

namespace App\Services;

use App\Models\Notification;
use App\Models\User;

class NotificationService
{
    /**
     * Create a notification for a specific user.
     * Prevents duplicate unread notifications of the same type+link for a user.
     */
    public static function send(int $userId, string $type, string $title, string $message, ?string $link = null): Notification
    {
        return Notification::create([
            'user_id' => $userId,
            'type'    => $type,
            'title'   => $title,
            'message' => $message,
            'link'    => $link,
            'is_read' => false,
        ]);
    }

    /**
     * Send notification to all active users
     */
    public static function broadcast(string $type, string $title, string $message, ?string $link = null): void
    {
        User::where('status', 'active')->chunk(100, function ($users) use ($type, $title, $message, $link) {
            foreach ($users as $user) {
                self::send($user->id, $type, $title, $message, $link);
            }
        });
    }

    /**
     * Send notification to all admins
     */
    public static function notifyAdmins(string $type, string $title, string $message, ?string $link = null): void
    {
        User::where('role', 'admin')->each(function ($user) use ($type, $title, $message, $link) {
            self::send($user->id, $type, $title, $message, $link);
        });
    }

    // ─── Event-specific helpers ──────────────────────────────────────────────

    /**
     * Welcome notification on new registration
     */
    public static function welcome(int $userId, string $userName): void
    {
        self::send(
            $userId,
            'welcome',
            'Hoş Geldiniz! 🎉',
            "Merhaba {$userName}! Askeri Platform'a hoş geldiniz. Sınav çöz, forum'da sor, kütüphaneyi keşfet.",
            route('dashboard')
        );
    }

    /**
     * Notify blog post author of a new comment
     */
    public static function newBlogComment(int $authorId, string $postTitle, string $commenterName, string $link): void
    {
        // Don't notify if author comments on their own post
        self::send(
            $authorId,
            'comment',
            'Yeni Yorum 💬',
            "{$commenterName}, \"{$postTitle}\" yazınıza yorum yaptı.",
            $link
        );
    }

    /**
     * Notify blog comment author when someone replies to their comment
     */
    public static function commentReply(int $commentAuthorId, string $postTitle, string $replierName, string $link): void
    {
        self::send(
            $commentAuthorId,
            'comment_reply',
            'Yorumunuza Yanıt 💬',
            "{$replierName}, \"{$postTitle}\" yazısındaki yorumunuza yanıt verdi.",
            $link
        );
    }

    /**
     * Notify forum topic owner of a new reply
     */
    public static function forumReply(int $topicOwnerId, string $topicTitle, string $replierName, string $link): void
    {
        self::send(
            $topicOwnerId,
            'forum_reply',
            'Forum Yanıtı 📝',
            "{$replierName}, \"{$topicTitle}\" konunuza yanıt verdi.",
            $link
        );
    }

    /**
     * Notify forum post author when their post is liked
     */
    public static function forumPostLiked(int $postAuthorId, string $topicTitle, string $likerName, string $link): void
    {
        self::send(
            $postAuthorId,
            'forum_like',
            'Mesajınız Beğenildi 👍',
            "{$likerName}, \"{$topicTitle}\" konusundaki mesajınızı beğendi.",
            $link
        );
    }

    /**
     * Notify user when they complete a quiz (score milestone)
     */
    public static function quizCompleted(int $userId, string $categoryName, int $score, string $link): void
    {
        $emoji = $score >= 90 ? '🥇' : ($score >= 70 ? '🎯' : '📊');
        self::send(
            $userId,
            'quiz',
            "Sınav Tamamlandı {$emoji}",
            "\"{$categoryName}\" sınavından %{$score} aldınız. " . ($score >= 70 ? 'Tebrikler!' : 'Tekrar deneyin!'),
            $link
        );
    }

    /**
     * Notify user of a new system announcement
     */
    public static function announcement(int $userId, string $title, string $message, ?string $link = null): void
    {
        self::send($userId, 'announcement', $title, $message, $link);
    }

    /**
     * Notify admins of a new user registration
     */
    public static function adminNewUser(string $userName, string $userEmail): void
    {
        self::notifyAdmins(
            'admin',
            'Yeni Üye Kaydı 👤',
            "{$userName} ({$userEmail}) platforma kayıt oldu.",
            route('admin.users.index')
        );
    }

    /**
     * Get unread count for user
     */
    public static function getUnreadCount(int $userId): int
    {
        return Notification::where('user_id', $userId)->where('is_read', false)->count();
    }
}
