<?php
/**
 * Provider for WordPress Posts.
 *
 * @package Replyan_AI
 */

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

class Replyan_AI_Post_Source_Provider implements Replyan_AI_Source_Provider_Interface {
	public function getDocuments(): array {
		$settings         = Replyan_AI_Settings::get();
		$index_permalinks = ! isset( $settings['index_permalinks'] ) || '0' !== (string) $settings['index_permalinks'];

		$posts = get_posts( array(
			'post_type'      => 'post',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
		) );

		$documents = array();
		foreach ( $posts as $post ) {
			$permalink      = get_permalink( $post->ID );
			$content_blocks = array();

			if ( $index_permalinks && $permalink ) {
				$content_blocks[] = 'Link: ' . $permalink;
			}

			$body_content = wp_strip_all_tags( strip_shortcodes( $post->post_content ) );
			if ( ! empty( trim( $body_content ) ) ) {
				$content_blocks[] = $body_content;
			}

			$documents[] = array(
				'source_type' => 'post',
				'source_id'   => $post->ID,
				'title'       => $post->post_title,
				'url'         => $permalink,
				'content'     => implode( "\n\n", $content_blocks ),
				'modified_at' => get_post_modified_time( 'Y-m-d H:i:s', false, $post->ID ),
			);
		}

		return $documents;
	}
}
