<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Log;

class AdminActivityLog extends Model
{
    protected $fillable = [
        'actor_user_id',
        'event_type',
        'category',
        'title',
        'message',
        'url',
        'context',
    ];

    protected function casts(): array
    {
        return [
            'context' => 'array',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

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

    /**
     * Safe activity logger; will never break main flow if logging fails.
     */
    public static function record(array $attributes): ?self
    {
        try {
            return self::create($attributes);
        } catch (\Throwable $e) {
            Log::warning('Failed to record admin activity log', [
                'event_type' => $attributes['event_type'] ?? null,
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }
}
