<?php

namespace App\Services\Support;

use Config\Database;

/**
 * Single write path into activity_logs (see 05-saas-architecture.md §6 for
 * why this is kept separate from audit_logs and subscription_usage).
 * Every module calls this the same way — controllers should not write to
 * activity_logs directly.
 */
class ActivityLogger
{
    public function log(
        ?int $userId,
        ?int $agencyId,
        ?string $role,
        string $action,
        array $metadata = []
    ): void {
        // request() is CI4's global helper for the shared Request instance.
        // (service('request', false) was a bug — that second argument gets
        // forwarded as the $config parameter to Services::request(), not
        // interpreted as a "don't share" flag, which crashed every code
        // path that logs activity — including registration and login.)
        $request = service('request');
        $isCli = $request instanceof \CodeIgniter\HTTP\CLIRequest;

        Database::connect()->table('activity_logs')->insert([
            'user_id'    => $userId,
            'agency_id'  => $agencyId,
            'role'       => $role,
            'action'     => $action,
            'ip_address' => $isCli ? null : $request?->getIPAddress(),
            'device'     => $metadata['device'] ?? null,
            'browser'    => $metadata['browser'] ?? ($isCli ? null : ($request?->getUserAgent()->getBrowser() ?? null)),
            'metadata'   => ! empty($metadata) ? json_encode($metadata) : null,
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }
}
