<?php

namespace App\Services\ESign;

use App\Models\ESign\EsignAuditLog;
use App\Services\Service;

class EsignAuditService extends Service
{
    public function log(
        int $contractId,
        string $action,
        ?int $signerId = null,
        ?array $metadata = null
    ): EsignAuditLog {
        $request = request();

        return EsignAuditLog::create([
            'tenant_id' => $this->tenantId(),
            'contract_id' => $contractId,
            'signer_id' => $signerId,
            'action' => $action,
            'ip_address' => $request?->ip(),
            'user_agent' => $request?->userAgent() ? mb_substr($request->userAgent(), 0, 500) : null,
            'metadata' => $metadata,
            'created_at' => now(),
        ]);
    }

    public function logPublic(
        int $tenantId,
        int $contractId,
        string $action,
        ?int $signerId = null,
        ?array $metadata = null
    ): EsignAuditLog {
        $request = request();

        return EsignAuditLog::withoutGlobalScopes()->create([
            'tenant_id' => $tenantId,
            'contract_id' => $contractId,
            'signer_id' => $signerId,
            'action' => $action,
            'ip_address' => $request?->ip(),
            'user_agent' => $request?->userAgent() ? mb_substr($request->userAgent(), 0, 500) : null,
            'metadata' => $metadata,
            'created_at' => now(),
        ]);
    }

    public function getContractLogs(int $contractId): \Illuminate\Database\Eloquent\Collection
    {
        return EsignAuditLog::where('contract_id', $contractId)
            ->with('signer:id,name,email,role')
            ->orderBy('created_at', 'desc')
            ->get();
    }
}
