<?php

namespace App\Services;

class AuditService
{
    public function log(string $action, string $entityType, ?int $entityId = null, array $metadata = []): void
    {
        try {
            db_connect()->table('audit_logs')->insert([
                'user_id' => auth_id(),
                'action' => $action,
                'entity_type' => $entityType,
                'entity_id' => $entityId,
                'ip_address' => service('request')->getIPAddress(),
                'user_agent' => substr((string) service('request')->getUserAgent(), 0, 500),
                'metadata' => json_encode($metadata, JSON_UNESCAPED_SLASHES),
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        } catch (\Throwable $e) {
            log_message('warning', 'Audit log write failed: {message}', ['message' => $e->getMessage()]);
        }
    }
}
