<?php
/**
 * Field ownership collision audit logger.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Audit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- scheduled_changes_ is the stable plugin prefix.

use ScheduledChanges\Domain\Audit\AuditEvent;
use ScheduledChanges\Field\OwnershipCollision;
use ScheduledChanges\Repository\AuditRepository;
use Throwable;

/**
 * Persists one redacted audit event per unique request-local collision.
 */
final class OwnershipCollisionLogger {
	private AuditRepository $audit;
	/**
	 * @var array<string,bool>
	 */
	private array $logged = array();

	public function __construct( AuditRepository $audit ) {
		$this->audit = $audit;
	}

	public function log( OwnershipCollision $collision ): void {
		$json = wp_json_encode( $collision->toArray() );
		$key  = hash( 'sha256', false === $json ? '' : $json );

		if ( isset( $this->logged[ $key ] ) ) {
			return;
		}

		$this->logged[ $key ] = true;

		try {
			$this->audit->record(
				AuditEvent::warning(
					'field.ownership_collision',
					get_current_user_id(),
					$collision->toArray()
				)
			);
		} catch ( Throwable $throwable ) {
			do_action( 'scheduled_changes_audit_write_failed', $throwable, $collision );
		}
	}
}
