<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Database\Eloquent\SoftDeletes;

class Notification extends Model
{
    use Prunable, SoftDeletes;

    protected $table = 'system_notifications';

    protected $fillable = [
        'title',
        'message',
        'recipient',
        'type',
        'read_at',
        'created_by',
    ];

    protected $casts = [
        'read_at' => 'datetime',
    ];

    /**
     * Get the user who created the notification.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Users who have interacted with this notification (read/deleted).
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'notification_user')
            ->withPivot('read_at', 'deleted_at')
            ->withTimestamps();
    }

    /**
     * Get the prunable model query.
     * Auto-delete notifications older than 30 days.
     */
    public function prunable(): Builder
    {
        return self::query()->where('created_at', '<=', now()->subDays(30));
    }
}
