<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class AudAuditTrail extends Model
{
    use Notifiable;

    protected $table = 'audit_trails';

    protected $fillable = [
        'id', 'resource', 'action', 'userid', 'response', 'status', 'created_at', 'created_by', 'ip_address',
        'mac_address', 'browser', 'date'
    ];

    /**
     * Write audit log entries defensively.
     * Audit logging must never block the underlying business transaction such as saving location settings.
     */
    public function postLogData($logdata): void
    {
        try {
            static::create([
                'resource' => $this->limitText($logdata['resource'] ?? '', 191),
                'action' => $this->limitText($logdata['action'] ?? '', 191),
                'userid' => $logdata['userid'] ?? null,
                'response' => $this->limitText($logdata['response'] ?? '', 191),
                'status' => $logdata['status'] ?? null,
                'ip_address' => $this->limitText($logdata['ip_address'] ?? '', 191),
                'mac_address' => $this->limitText($logdata['mac_address'] ?? '', 191),
                'browser' => $this->limitText($logdata['browser'] ?? '', 500),
                'date' => $logdata['date'] ?? now()->toDateString(),
                'created_at' => $logdata['now'] ?? now(),
                'created_by' => $logdata['userid'] ?? null,
            ]);
        } catch (\Throwable $exception) {
            Log::warning('NGBVD audit trail write skipped; primary action was not rolled back.', [
                'message' => $exception->getMessage(),
                'resource' => $logdata['resource'] ?? null,
                'action' => $logdata['action'] ?? null,
                'user_id' => $logdata['userid'] ?? null,
            ]);
        }
    }

    private function limitText($value, int $limit): ?string
    {
        if ($value === null) {
            return null;
        }

        return Str::limit((string) $value, $limit, '');
    }
}
