<?php
/**
 * oEmbed cache posts cleanup task.
 *
 * @package DatabaseCleanup
 */

namespace DatabaseCleanup\Includes\Tasks;

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

class Task_Oembed_Caches extends Abstract_Cleanup_Task {

	public function get_id(): string {
		return 'oembed_caches';
	}

	public function get_label(): string {
		return __( 'oEmbed caches', 'wppowersuite-lite' );
	}

	public function get_description(): string {
		return __( 'Remove cached oEmbed response posts stored in the database.', 'wppowersuite-lite' );
	}

	public function is_safe(): bool {
		return true;
	}

	public function scan( array $settings ): array {
		global $wpdb;

		unset( $settings );

		$count = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s",
				'oembed_cache'
			)
		);

		return [
			'count'           => $count,
			'estimated_bytes' => $this->estimate_row_bytes( $count, 2048 ),
			'details'         => [],
		];
	}

	public function clean( array $settings, int $batch_size, mixed $cursor = null ): array {
		global $wpdb;

		unset( $settings, $cursor );

		$ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT ID FROM {$wpdb->posts}
				WHERE post_type = %s
				ORDER BY ID ASC
				LIMIT %d",
				'oembed_cache',
				$batch_size
			)
		);

		$deleted = 0;
		$bytes   = 0;

		foreach ( $ids as $id ) {
			$post = get_post( (int) $id );
			if ( $post ) {
				$bytes += strlen( (string) $post->post_content ) + 256;
			}
			if ( wp_delete_post( (int) $id, true ) ) {
				++$deleted;
			}
		}

		$remaining = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s",
				'oembed_cache'
			)
		);

		return [
			'deleted' => $deleted,
			'done'    => $remaining === 0,
			'cursor'  => null,
			'bytes'   => $bytes,
		];
	}
}
