<?php

namespace App\Models\Messenger;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Builder;

class UserEvent extends Model
{
    protected $fillable = [
        'user_id',
        'event_type',
        'event_data',
        'related_id',
        'related_type',
    ];

    protected $casts = [
        'event_data' => 'array',
        'created_at' => 'datetime',
    ];

    public $timestamps = false;

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

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

    public function scopeSince(Builder $query, int $sinceId): Builder
    {
        return $query->where('id', '>', $sinceId);
    }

    public function scopeOfType(Builder $query, string $eventType): Builder
    {
        return $query->where('event_type', $eventType);
    }

    public function scopeRecent(Builder $query, int $limit = 100): Builder
    {
        return $query->orderBy('id', 'desc')->limit($limit);
    }

    public static function createEvent(int $userId, string $eventType, array $eventData, ?int $relatedId = null, ?string $relatedType = null): self
    {
        return self::create([
            'user_id' => $userId,
            'event_type' => $eventType,
            'event_data' => $eventData,
            'related_id' => $relatedId,
            'related_type' => $relatedType,
            'created_at' => now(),
        ]);
    }
}
