<?php
defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Duplicate-check queries on plugin-owned tables; $table = $wpdb->prefix . constant; user values use prepare() %s placeholders.

/**
 * Validation helpers for production creation.
 */
final class Costudio_Admin_Production_Validator {

	private function __construct() {
	}

	/**
	 * Validate production inputs per article type.
	 *
	 * @return string|null Error message or null if valid.
	 */
	public static function validate_inputs( array $inputs ): ?string {
		$type = Costudio_Article_Types::normalize( $inputs['article_type'] ?? '' );
		$lang = (string) ( $inputs['lang_code'] ?? '' );

		if ( ! Costudio_Admin::is_supported_content_language( $lang ) ) {
			return __( 'Invalid content language.', 'contentosapp-studio' );
		}

		if ( empty( trim( $inputs['keyword'] ?? '' ) ) ) {
			return __( 'Keyword is required.', 'contentosapp-studio' );
		}

		$extensao = $inputs['extensao'] ?? '';
		if ( ! empty( $extensao ) && ! preg_match( '/^\s*\d+\s*[-–]\s*\d+\s*$/', $extensao ) ) {
			return __( 'Word count range must be in the format "min-max" (e.g. 2000-2600).', 'contentosapp-studio' );
		}

		switch ( $type ) {
			case Costudio_Article_Types::COMPARISON:
				$items       = $inputs['comparison_items'] ?? array();
				$valid_items = array_filter(
					$items,
					static function ( $item ) {
						return ! empty( trim( $item['label'] ?? '' ) );
					}
				);
				if ( count( $valid_items ) < 2 ) {
					return __( 'Comparative articles require at least 2 items with labels to compare.', 'contentosapp-studio' );
				}
				break;

			case Costudio_Article_Types::NEWS:
				$sources       = $inputs['news_sources'] ?? array();
				$valid_sources = array_filter(
					$sources,
					static function ( $s ) {
						return ! empty( trim( $s['url'] ?? '' ) ) && filter_var( $s['url'], FILTER_VALIDATE_URL );
					}
				);
				if ( empty( $valid_sources ) ) {
					return __( 'News articles require at least one valid source URL.', 'contentosapp-studio' );
				}

				// Author validation — the news byline and the NewsArticle schema
				// (author.Person) both depend on a real WP user. Reject early so
				// the pipeline never runs without a resolvable author identity.
				$author_id = (int) ( $inputs['news_author_id'] ?? 0 );
				if ( $author_id <= 0 ) {
					return __( 'Please select the author of the news article before producing.', 'contentosapp-studio' );
				}
				$author = get_userdata( $author_id );
				if ( ! $author || ! user_can( $author, 'edit_posts' ) ) {
					return __( 'The selected author does not exist or lacks permission to publish posts. Choose a user with Administrator, Editor, or Author role.', 'contentosapp-studio' );
				}
				break;

			case Costudio_Article_Types::UPDATE:
				$url = $inputs['update_post_url'] ?? '';
				if ( empty( $url ) ) {
					return __( 'Update articles require the original post URL.', 'contentosapp-studio' );
				}
				if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
					return sprintf(
						/* translators: %s: the invalid URL the user submitted */
						__( 'Invalid URL for the original post: "%s". Please provide a valid URL.', 'contentosapp-studio' ),
						esc_html( $url )
					);
				}
				if ( empty( trim( $inputs['update_instructions'] ?? '' ) ) ) {
					return __( 'Update articles require instructions describing what to change.', 'contentosapp-studio' );
				}
				$content = (string) ( $inputs['update_post_content'] ?? '' );
				if ( '' === trim( $content ) || false === strpos( $content, '<!-- wp:' ) ) {
					return __( 'Update articles require raw Gutenberg block markup from the original post.', 'contentosapp-studio' );
				}
				break;
		}

		return null;
	}

	public static function check_keyword_duplicate( string $site_key, string $keyword ): ?string {
		if ( empty( $keyword ) || empty( $site_key ) ) {
			return null;
		}

		global $wpdb;
		$table  = $wpdb->prefix . Costudio_Production::TABLE;
		$exists = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM {$table} WHERE site_key = %s AND keyword = %s AND status = 'completed' LIMIT 1",
				$site_key,
				$keyword
			)
		);

		if ( $exists ) {
			return sprintf(
				/* translators: 1: keyword, 2: production ID */
				__( '⚠️ Keyword "%1$s" was already used on this site (production #%2$s). Consider a different angle to avoid SEO cannibalization.', 'contentosapp-studio' ),
				$keyword,
				$exists
			);
		}

		return null;
	}
}
