<?php

namespace VendorTasksDokanClickUp\Queue;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Activity Log
 *
 * Lightweight option-based ring buffer storing the last 20 plugin events.
 * Written to on task creation and failure; read by OverviewController.
 *
 * @since 1.5.0
 * @package VendorTasksDokanClickUp
 * @subpackage Queue
 */
class ActivityLog {

	/**
	 * WP option name (non-autoloaded)
	 */
	private const OPTION = 'vendor_tasks_dokan_clickup_activity_log';

	/**
	 * Maximum entries to keep.
	 */
	private const MAX = 20;

	/**
	 * Append an event to the log.
	 *
	 * @since 1.5.0
	 *
	 * @param string $event      Human-readable event name (e.g. 'New Vendor Registration').
	 * @param string $vendor     Vendor display name or shop name.
	 * @param string $status     'Created', 'Updated', 'Failed', 'Comment added', etc.
	 * @param int    $vendor_id  Vendor user ID (for context).
	 * @return void
	 */
	public function push( string $event, string $vendor, string $status, int $vendor_id = 0 ): void {
		$log   = $this->get_all();
		$entry = array(
			'event'     => $event,
			'vendor'    => $vendor,
			'status'    => $status,
			'vendor_id' => $vendor_id,
			'ts'        => time(),
		);
		array_unshift( $log, $entry );
		$log = array_slice( $log, 0, self::MAX );
		update_option( self::OPTION, $log, false );
	}

	/**
	 * Return all stored log entries (newest first).
	 *
	 * @since 1.5.0
	 *
	 * @return array<int, array{event: string, vendor: string, status: string, vendor_id: int, ts: int}>
	 */
	public function get_all(): array {
		$log = get_option( self::OPTION, array() );
		return is_array( $log ) ? $log : array();
	}

	/**
	 * Clear the log.
	 *
	 * @since 1.5.0
	 *
	 * @return void
	 */
	public function clear(): void {
		delete_option( self::OPTION );
	}
}
