<?php

/**
 * CommentHandler — Domain handler for comment read/write actions.
 *
 * Owns: get_comments, manage_comments
 *
 * @package LolaCore\Actions\Handlers
 * @license GPL-2.0-or-later
 */

declare( strict_types=1 );

namespace LolaCore\Actions\Handlers;

use LolaCore\Actions\Contracts\ActionHandlerInterface;

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

/**
 * Handles get_comments and manage_comments actions.
 */
class CommentHandler implements ActionHandlerInterface {

	private const MAX_BULK = 50;

	/** @inheritDoc */
	public function getSupportedActions(): array {
		return array( 'get_comments', 'manage_comments' );
	}

	/** @inheritDoc */
	public function handle( string $actionId, array $params, bool $dryRun ): array {
		return match ( $actionId ) {
			'get_comments'    => $this->getComments( $params ),
			'manage_comments' => $this->manageComments( $params, $dryRun ),
			default           => throw new \Exception( esc_html( "CommentHandler: unknown action '{$actionId}'." ) ),
		};
	}

	private function getComments( array $params ): array {
		$status  = $params['status'] ?? 'approve';
		$post_id = isset( $params['post_id'] ) ? (int) $params['post_id'] : 0;
		$limit   = isset( $params['limit'] ) ? (int) $params['limit'] : 20;

		$args = array( 'number' => $limit );
		if ( $status !== 'all' ) {
			$args['status'] = $status;
		}
		if ( $post_id > 0 ) {
			$args['post_id'] = $post_id;
		}

		$comments = get_comments( $args );
		$data     = array();
		foreach ( $comments as $c ) {
			$data[] = array(
				'id'      => $c->comment_ID,
				'post_id' => $c->comment_post_ID,
				'author'  => $c->comment_author,
				'date'    => $c->comment_date,
				'content' => mb_substr( wp_strip_all_tags( $c->comment_content ), 0, 300 ),
				'status'  => $c->comment_approved,
			);
		}
		return array( 'comments' => $data, 'count' => count( $data ) );
	}

	private function manageComments( array $params, bool $dryRun ): array {
		$comment_ids = $params['comment_ids'] ?? array();
		$action      = $params['action'] ?? '';

		if ( empty( $comment_ids ) || ! is_array( $comment_ids ) ) {
			throw new \Exception( 'comment_ids array is required.' );
		}
		if ( ! in_array( $action, array( 'approve', 'hold', 'spam', 'trash', 'delete' ), true ) ) {
			throw new \Exception( "Invalid action. Use 'approve', 'hold', 'spam', 'trash', or 'delete'." );
		}
		if ( count( $comment_ids ) > self::MAX_BULK ) {
			throw new \Exception( 'Maximum 50 comments per operation.' );
		}

		if ( $dryRun ) {
			return array(
				'action'      => "Will {$action} comments",
				'comment_ids' => $comment_ids,
				'count'       => count( $comment_ids ),
			);
		}

		$success = 0;
		$failed  = 0;
		foreach ( $comment_ids as $cid ) {
			$cid = (int) $cid;
			if ( $action === 'delete' ) {
				wp_delete_comment( $cid, true ) ? $success++ : $failed++;
			} else {
				wp_set_comment_status( $cid, $action ) ? $success++ : $failed++;
			}
		}

		return array(
			'success' => $success > 0,
			'message' => "Successfully {$action}ed {$success} comment(s). Failed: {$failed}.",
			'updated' => $success,
			'failed'  => $failed,
		);
	}
}
