<?php
/**
 * Default-term seed data for vehicle taxonomies + first-run dealer post.
 *
 * Extracted from `Activator` in QUALITY-IMPROVEMENT-PLAN T2-2e — the term
 * data (260L of literal Make→Models, feature lists, etc.) and the helpers
 * that own its shape don't belong in the activation orchestrator. `Activator`
 * stays the public surface and delegates here for taxonomy registration
 * args + default term insertion + first-dealer creation.
 *
 * All methods are public-static so `Activator` and any future tooling can
 * call them in isolation. `wp_insert_term` silently skips duplicates and
 * `update_term_meta` overwrites, so every method is safe to re-run.
 *
 * @package ThemeREX\AutoDealer\Core\Activation
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Core\Activation;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\PostTypes\DealerPostType;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

final class TermSeeder {

	/**
	 * Register all vehicle taxonomies inline. Used by `Activator::activate()`
	 * because at activation time the `init` hook hasn't fired yet, so the
	 * normal Taxonomy classes haven't registered their CPT-bound taxonomies.
	 *
	 * @return void
	 */
	public static function registerTaxonomies(): void {
		foreach ( self::getTaxonomyDefinitions() as $slug => $args ) {
			if ( ! taxonomy_exists( $slug ) ) {
				register_taxonomy( $slug, VehiclePostType::POST_TYPE, $args );
			}
		}
	}

	/**
	 * Insert default terms for all vehicle taxonomies.
	 *
	 * Idempotent — `wp_insert_term` skips dupes. Re-running is harmless.
	 *
	 * @return void
	 */
	public static function insertDefaultTerms(): void {
		$defaults = self::getDefaultTerms();

		foreach ( $defaults as $taxonomy => $terms ) {
			if ( ! taxonomy_exists( $taxonomy ) ) {
				continue;
			}

			foreach ( $terms as $term ) {
				if ( is_array( $term ) ) {
					// Make + its models. Models live in a SEPARATE taxonomy
					// (`trx_ad_model`); we link them to the parent make via
					// `_trx_ad_model_make` term meta because WP's built-in
					// taxonomy `parent` only supports same-taxonomy parents.
					$make_name = is_string( $term[0] ?? null ) ? $term[0] : '';
					if ( '' === $make_name ) {
						continue;
					}
					$make_result  = wp_insert_term( $make_name, $taxonomy );
					$make_term_id = 0;

					if ( ! is_wp_error( $make_result ) ) {
						$make_term_id = (int) $make_result['term_id'];
					} elseif ( isset( $make_result->error_data['term_exists'] ) ) {
						$make_term_id = (int) $make_result->error_data['term_exists'];
					}

					if ( $make_term_id > 0
						&& isset( $term[1] )
						&& is_array( $term[1] )
						&& taxonomy_exists( 'trx_ad_model' ) ) {
						foreach ( $term[1] as $model_name ) {
							$model_result = wp_insert_term( (string) $model_name, 'trx_ad_model' );
							$model_id     = 0;
							if ( ! is_wp_error( $model_result ) ) {
								$model_id = (int) $model_result['term_id'];
							} elseif ( isset( $model_result->error_data['term_exists'] ) ) {
								$model_id = (int) $model_result->error_data['term_exists'];
							}
							if ( $model_id > 0 ) {
								update_term_meta( $model_id, '_trx_ad_model_make', $make_term_id );
							}
						}
					}
				} else {
					wp_insert_term( (string) $term, $taxonomy );
				}
			}
		}
	}

	/**
	 * Create a default dealer post if none exists.
	 *
	 * @return void
	 */
	public static function createDefaultDealer(): void {
		$existing = get_posts(
			array(
				'post_type'      => DealerPostType::POST_TYPE,
				'posts_per_page' => 1,
				'post_status'    => 'any',
				'fields'         => 'ids',
			)
		);

		if ( ! empty( $existing ) ) {
			return;
		}

		wp_insert_post(
			array(
				'post_type'   => DealerPostType::POST_TYPE,
				'post_title'  => __( 'My Dealership', 'trx-auto-dealer' ),
				'post_status' => 'publish',
				'post_author' => (int) get_current_user_id() ?: 1,
			)
		);
	}

	/**
	 * Taxonomy registration arguments. Public so `Activator::registerTaxonomies`
	 * (run at activate-time before `init`) and any future migration tooling can
	 * use the same definitions.
	 *
	 * @return array<string, array<string, mixed>>
	 */
	public static function getTaxonomyDefinitions(): array {
		$hierarchical_args = static function ( string $singular, string $plural ): array {
			return array(
				'labels'            => array(
					'name'          => $plural,
					'singular_name' => $singular,
					'search_items'  => sprintf( 'Search %s', $plural ),
					'all_items'     => sprintf( 'All %s', $plural ),
					'parent_item'   => sprintf( 'Parent %s', $singular ),
					'edit_item'     => sprintf( 'Edit %s', $singular ),
					'add_new_item'  => sprintf( 'Add New %s', $singular ),
				),
				'hierarchical'      => true,
				'show_ui'           => true,
				'show_admin_column' => true,
				'show_in_rest'      => true,
				'rewrite'           => false,
			);
		};

		$flat_args = static function ( string $singular, string $plural ): array {
			return array(
				'labels'            => array(
					'name'          => $plural,
					'singular_name' => $singular,
					'search_items'  => sprintf( 'Search %s', $plural ),
					'all_items'     => sprintf( 'All %s', $plural ),
					'edit_item'     => sprintf( 'Edit %s', $singular ),
					'add_new_item'  => sprintf( 'Add New %s', $singular ),
				),
				'hierarchical'      => false,
				'show_ui'           => true,
				'show_admin_column' => true,
				'show_in_rest'      => true,
				'rewrite'           => false,
			);
		};

		return array(
			// Make + Model are flat taxonomies. Model→Make linkage is via
			// the `_trx_ad_model_make` term meta (managed by ModelMakeLink).
			'trx_ad_make'         => $flat_args( 'Make', 'Makes' ),
			'trx_ad_model'        => $flat_args( 'Model', 'Models' ),
			'trx_ad_body_style'   => $flat_args( 'Body Style', 'Body Styles' ),
			'trx_ad_fuel_type'    => $flat_args( 'Fuel Type', 'Fuel Types' ),
			'trx_ad_transmission' => $flat_args( 'Transmission', 'Transmissions' ),
			'trx_ad_drivetrain'   => $flat_args( 'Drivetrain', 'Drivetrains' ),
			'trx_ad_color'        => $flat_args( 'Color', 'Colors' ),
			'trx_ad_feature'      => $flat_args( 'Feature', 'Features' ),
			'trx_ad_vehicle_type' => $flat_args( 'Vehicle Type', 'Vehicle Types' ),
			'trx_ad_condition'    => $flat_args( 'Condition', 'Conditions' ),
		);
	}

	/**
	 * Default terms for each taxonomy. Bump `Activator::SEED_VERSION` when
	 * this shape changes so `ensureUpgraded()` re-applies on existing sites.
	 *
	 * @return array<string, array<int, string|array<int, string|array<int, string>>>>
	 */
	public static function getDefaultTerms(): array {
		return array(
			'trx_ad_vehicle_type' => array(
				'Car',
				'Truck',
				'Motorcycle',
				'Boat',
				'RV',
				'ATV',
				'Commercial',
			),
			'trx_ad_condition'    => array(
				'New',
				'Used',
				'Certified Pre-Owned',
			),
			'trx_ad_fuel_type'    => array(
				'Gasoline',
				'Diesel',
				'Electric',
				'Hybrid',
				'PHEV',
				'Hydrogen',
				'LPG',
				'CNG',
				'Flex Fuel',
			),
			'trx_ad_transmission' => array(
				'Automatic',
				'Manual',
				'CVT',
				'Semi-Automatic',
				'Dual-Clutch',
			),
			'trx_ad_drivetrain'   => array(
				'FWD',
				'RWD',
				'AWD',
				'4WD',
			),
			'trx_ad_body_style'   => array(
				'Sedan',
				'SUV',
				'Coupe',
				'Convertible',
				'Hatchback',
				'Wagon',
				'Van',
				'Minivan',
				'Pickup Truck',
				'Crossover',
				'Sports Car',
				'Luxury',
			),
			'trx_ad_color'        => array(
				'Black',
				'White',
				'Silver',
				'Gray',
				'Red',
				'Blue',
				'Green',
				'Brown',
				'Beige',
				'Yellow',
				'Orange',
				'Gold',
				'Other',
			),
			'trx_ad_feature'      => array(
				'Air Conditioning',
				'Bluetooth',
				'Backup Camera',
				'Cruise Control',
				'Navigation System',
				'Sunroof',
				'Leather Seats',
				'Heated Seats',
				'Apple CarPlay',
				'Android Auto',
				'Parking Sensors',
				'Lane Assist',
				'Blind Spot Monitor',
				'Keyless Entry',
				'Push Button Start',
				'Alloy Wheels',
				'Tow Package',
				'Third Row Seating',
				'Roof Rack',
				'LED Headlights',
			),
			'trx_ad_make'         => array(
				array( 'Acura', array( 'ILX', 'TLX', 'MDX', 'RDX', 'Integra' ) ),
				array( 'Audi', array( 'A3', 'A4', 'A6', 'Q3', 'Q5', 'Q7', 'e-tron' ) ),
				array( 'BMW', array( '3 Series', '5 Series', 'X1', 'X3', 'X5', 'iX' ) ),
				array( 'Chevrolet', array( 'Malibu', 'Camaro', 'Corvette', 'Equinox', 'Tahoe', 'Silverado', 'Colorado' ) ),
				array( 'Dodge', array( 'Challenger', 'Charger', 'Durango', 'Hornet' ) ),
				array( 'Ford', array( 'Mustang', 'F-150', 'Explorer', 'Escape', 'Bronco', 'Maverick', 'Edge' ) ),
				array( 'GMC', array( 'Sierra', 'Terrain', 'Acadia', 'Yukon', 'Canyon' ) ),
				array( 'Honda', array( 'Civic', 'Accord', 'CR-V', 'HR-V', 'Pilot', 'Ridgeline', 'Odyssey' ) ),
				array( 'Hyundai', array( 'Elantra', 'Sonata', 'Tucson', 'Santa Fe', 'Kona', 'Ioniq 5', 'Palisade' ) ),
				array( 'Jeep', array( 'Wrangler', 'Grand Cherokee', 'Cherokee', 'Compass', 'Gladiator', 'Renegade' ) ),
				array( 'Kia', array( 'Forte', 'K5', 'Sportage', 'Telluride', 'Sorento', 'EV6', 'Soul' ) ),
				array( 'Lexus', array( 'ES', 'IS', 'NX', 'RX', 'GX', 'LX' ) ),
				array( 'Mazda', array( 'Mazda3', 'Mazda6', 'CX-5', 'CX-50', 'CX-9', 'MX-5 Miata' ) ),
				array( 'Mercedes-Benz', array( 'C-Class', 'E-Class', 'S-Class', 'GLA', 'GLC', 'GLE', 'EQS' ) ),
				array( 'Nissan', array( 'Altima', 'Sentra', 'Rogue', 'Pathfinder', 'Frontier', 'LEAF', 'Ariya' ) ),
				array( 'Ram', array( '1500', '2500', '3500', 'ProMaster' ) ),
				array( 'Subaru', array( 'Impreza', 'Legacy', 'Outback', 'Forester', 'Crosstrek', 'WRX', 'Solterra' ) ),
				array( 'Tesla', array( 'Model 3', 'Model Y', 'Model S', 'Model X', 'Cybertruck' ) ),
				array( 'Toyota', array( 'Camry', 'Corolla', 'RAV4', 'Highlander', 'Tacoma', 'Tundra', '4Runner', 'Prius', 'Supra' ) ),
				array( 'Volkswagen', array( 'Jetta', 'Passat', 'Golf', 'Tiguan', 'Atlas', 'ID.4', 'Taos' ) ),
			),
			'trx_ad_model'        => array(),
		);
	}
}
