<?php

namespace AIPT\Api\Dashboard;

use AIPT\Core\Services\UsageTracker;

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

class DashboardRepository {

	public function fetchGenerations( int $limit ): array {
		return UsageTracker::get_recent_events( $this->normalize_limit( $limit ) );
	}

	public function fetchChatbotActivity( int $limit ): array {
		global $wpdb;

		$chatbot_table = $wpdb->prefix . 'aipt_chatbot_messages';

		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, status, record_type, user_name, LEFT(message, 160) AS message_excerpt, ai_response IS NOT NULL AS has_ai_response, created_at
				 FROM {$chatbot_table}
				 WHERE record_type IN (%s, %s)
				 ORDER BY created_at DESC
				 LIMIT %d",
				'error',
				'conversation',
				$this->normalize_limit( $limit )
			),
			ARRAY_A
		);

		return is_array( $rows ) ? $rows : array();
	}

	public function fetchJobs( int $limit ): array {
		global $wpdb;

		$jobs_table = $wpdb->prefix . 'aipt_automation_jobs';

		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, name, status, created_at
				 FROM {$jobs_table}
				 ORDER BY created_at DESC
				 LIMIT %d",
				$this->normalize_limit( $limit )
			),
			ARRAY_A
		);

		return is_array( $rows ) ? $rows : array();
	}

	private function normalize_limit( int $limit ): int {
		return max( 1, min( 10, $limit ) );
	}
}
