<?php
/**
 * Characterization tests for Ppok\AIToolkit\Event_Logger.
 *
 * @package Ppok\AIToolkit\Tests
 * @license GPL-2.0-or-later
 */

namespace Ppok\AIToolkit\Tests;

use Ppok\AIToolkit\Event_Logger;

class Test_Event_Logger extends \WP_UnitTestCase {

	public function test_table_exists_after_activation(): void {
		global $wpdb;
		$table = Event_Logger::table_name();
		$result = $wpdb->get_var( "SHOW TABLES LIKE '{$table}'" );
		$this->assertSame( $table, $result, 'Expected events table to exist after activation.' );
	}

	public function test_db_version_option_seeded_on_activation(): void {
		$this->assertSame( Event_Logger::DB_VERSION, get_option( Event_Logger::DB_VERSION_OPTION ) );
	}

	public function test_record_inserts_row_and_returns_id(): void {
		global $wpdb;
		$logger = new Event_Logger();

		$id = $logger->record(
			array(
				'ability_slug'   => 'ppok/test/example',
				'actor_user_id'  => 5,
				'target_post_id' => 42,
				'reason'         => 'test rationale',
				'result'         => 'ok',
				'duration_ms'    => 123,
				'mcp_client'     => 'PHPUnit/test',
				'correlation_id' => 'cor-1',
				'payload'        => array( 'diff' => array( 'blocks_added' => 1 ) ),
			)
		);

		$this->assertGreaterThan( 0, $id );

		$row = $wpdb->get_row(
			$wpdb->prepare( 'SELECT * FROM ' . Event_Logger::table_name() . ' WHERE id = %d', $id ),
			ARRAY_A
		);

		$this->assertNotNull( $row, 'Row should be retrievable after record().' );
		$this->assertSame( 'ppok/test/example', $row['ability_slug'] );
		$this->assertEquals( 5, $row['actor_user_id'] );
		$this->assertEquals( 42, $row['target_post_id'] );
		$this->assertSame( 'test rationale', $row['reason'] );
		$this->assertSame( 'ok', $row['result'] );
		$this->assertSame( 'PHPUnit/test', $row['mcp_client'] );
		$this->assertSame( 'cor-1', $row['correlation_id'] );
		$this->assertSame( '{"diff":{"blocks_added":1}}', $row['payload'] );
	}

	public function test_truncates_oversize_string_fields(): void {
		global $wpdb;
		$logger = new Event_Logger();

		$id = $logger->record(
			array(
				'ability_slug' => str_repeat( 'a', 300 ),
				'reason'       => str_repeat( 'b', 600 ),
				'result'       => 'validation_error',
			)
		);

		$row = $wpdb->get_row(
			$wpdb->prepare( 'SELECT * FROM ' . Event_Logger::table_name() . ' WHERE id = %d', $id ),
			ARRAY_A
		);

		$this->assertSame( 191, strlen( $row['ability_slug'] ) );
		$this->assertSame( 500, strlen( $row['reason'] ) );
		$this->assertSame( 'validation_error', $row['result'] );
	}

	public function test_record_defaults_result_to_server_error_when_missing(): void {
		$logger = new Event_Logger();
		$id     = $logger->record( array( 'ability_slug' => 'ppok/test/no-result' ) );

		global $wpdb;
		$result = $wpdb->get_var(
			$wpdb->prepare( 'SELECT result FROM ' . Event_Logger::table_name() . ' WHERE id = %d', $id )
		);

		$this->assertSame( 'server_error', $result );
	}
}
