<?php

namespace App\Services\Marketplace;

use App\Core\App;

/**
 * ITSWEBER CMS – Marketplace Audit Logger
 *
 * Records every install/update/rollback/allowlist attempt in iw_marketplace_install_log.
 * Silently fails if the table is unavailable so logging never breaks the app.
 */
class MarketplaceAuditLogger
{
    /**
     * Record a marketplace action.
     *
     * @param array{
     *   slug:           string,
     *   type:           string,
     *   action:         string,
     *   version_target: string,
     *   registry_url:   string,
     *   key_id:         string,
     *   sha256_verified: bool,
     *   sig_verified:   bool,
     *   result:         string,
     *   error_message?: string|null,
     *   backup_path?:   string|null,
     *   user_id?:       int|null,
     * } $fields
     */
    public static function record(array $fields): void
    {
        try {
            $app = App::getInstance();
            if (!$app) {
                return;
            }

            $db = $app->service('database');

            $userId = $fields['user_id'] ?? null;
            if ($userId === null && $app->hasService('auth')) {
                $userId = $app->service('auth')->userId() ?? null;
            }

            $db->insert('iw_marketplace_install_log', [
                'slug'            => mb_substr((string) ($fields['slug']            ?? ''), 0, 100),
                'type'            => in_array($fields['type'] ?? '', ['plugin', 'theme'], true) ? $fields['type'] : 'plugin',
                'action'          => $fields['action']          ?? 'install',
                'version_target'  => mb_substr((string) ($fields['version_target']  ?? ''), 0, 20),
                'registry_url'    => mb_substr((string) ($fields['registry_url']    ?? ''), 0, 500),
                'key_id'          => mb_substr((string) ($fields['key_id']          ?? ''), 0, 32),
                'sha256_verified' => (int) ($fields['sha256_verified'] ?? 0),
                'sig_verified'    => (int) ($fields['sig_verified']    ?? 0),
                'result'          => $fields['result'] ?? 'success',
                'error_message'   => $fields['error_message'] ?? null,
                'backup_path'     => isset($fields['backup_path']) ? mb_substr((string) $fields['backup_path'], 0, 500) : null,
                'user_id'         => $userId,
                'ip_address'      => mb_substr((string) ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'), 0, 45),
            ]);
        } catch (\Throwable $e) {
            // Logging must never break the application
        }
    }
}
