<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ForumNotification extends Model
{
    protected $fillable = [
        'user_id',
        'post_id',
        'topic_id',
        'from_user_id',
        'type',
        'message',
        'is_read',
    ];

    protected $casts = [
        'is_read' => 'boolean',
    ];

    // ── Relationships ──────────────────────────────────────────────────────

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function fromUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'from_user_id');
    }

    public function post(): BelongsTo
    {
        return $this->belongsTo(ForumPost::class);
    }

    public function topic(): BelongsTo
    {
        return $this->belongsTo(ForumTopic::class);
    }

    // ── Scopes ─────────────────────────────────────────────────────────────

    public function scopeUnread($query)
    {
        return $query->where('is_read', false);
    }

    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    // ── Helpers ─────────────────────────────────────────────────────────────

    public static function notify(int $userId, string $type, array $data = []): void
    {
        // Do not notify yourself
        if ($userId === ($data['from_user_id'] ?? null)) {
            return;
        }

        $typeMessages = [
            'reply'   => ($data['from_user_name'] ?? 'Biri') . ' konunuza yanıt verdi.',
            'quote'   => ($data['from_user_name'] ?? 'Biri') . ' mesajınızı alıntıladı.',
            'like'    => ($data['from_user_name'] ?? 'Biri') . ' mesajınızı beğendi.',
            'mention' => ($data['from_user_name'] ?? 'Biri') . ' sizi bir konuda etiketledi.',
        ];

        static::create([
            'user_id'      => $userId,
            'from_user_id' => $data['from_user_id'] ?? null,
            'post_id'      => $data['post_id'] ?? null,
            'topic_id'     => $data['topic_id'] ?? null,
            'type'         => $type,
            'message'      => $data['message'] ?? ($typeMessages[$type] ?? ''),
            'is_read'      => false,
        ]);
    }

    public function markAsRead(): void
    {
        $this->update(['is_read' => true]);
    }

    public static function markAllAsRead(int $userId): int
    {
        return static::forUser($userId)->unread()->update(['is_read' => true]);
    }

    public static function unreadCount(int $userId): int
    {
        return static::forUser($userId)->unread()->count();
    }

    /**
     * Get human-readable label for notification type.
     */
    public function getTypeLabel(): string
    {
        return match($this->type) {
            'reply'      => '💬 Yanıt',
            'quote'      => '📝 Alıntı',
            'like'       => '👍 Beğeni',
            'mention'    => '📣 Etiket',
            'moderation' => '🛡️ Moderasyon',
            default      => 'Bildirim',
        };
    }

    /**
     * Get URL for the notification.
     */
    public function getUrl(): string
    {
        if ($this->post && $this->topic) {
            $topic = $this->topic->load('category');
            return route('forum.topic', [
                'category' => $topic->category->slug,
                'topic'    => $topic->slug,
            ]) . '#post-' . $this->post_id;
        }

        if ($this->topic) {
            $topic = $this->topic->load('category');
            return route('forum.topic', [
                'category' => $topic->category->slug,
                'topic'    => $topic->slug,
            ]);
        }

        return route('forum.index');
    }
}
