<?php
/**
 * File Path: includes/data/class-mbs-collection-seeder.php
 *
 * Collection Seeder
 *
 * Manages the initial population of the mbs_collection taxonomy.
 * Version 3: No terms are seeded. The type selector dropdown is driven
 * entirely by MBS_Taxonomy_Collection::get_types() (code) and does not require
 * pre-existing terms. When upgrading from v2, the 16 legacy terms are
 * deleted automatically unless a term has been assigned to at least one
 * book (those are left in place).
 *
 * Hooked by MBS_Plugin at init priority 20 (after taxonomy registration
 * at priority 10).
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Data
 * @since      1.0.0
 */

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

class MBS_Collection_Seeder {

	const SEEDED_OPTION  = 'mbs_collections_seeded';
	const SEEDED_VERSION = '3';

	/**
	 * Terms that were planted by version 2 of the seeder.
	 * Stored here so the v2 → v3 migration can remove them.
	 * Terms that have books assigned are intentionally left in place.
	 */
	const LEGACY_TERMS = array(
		'Anthology',
		'Author Collection',
		'Award-Winning Collection',
		'Book Club / Reading Challenge',
		'Box Set',
		'Bundle',
		'Companion / Spin-off',
		'Compendium',
		'Diversity & Representation',
		'Historical / Era Collection',
		'Limited Series',
		'Omnibus',
		"Publisher's Collection",
		'Seasonal / Holiday',
		'Special Edition',
		'Themed Collection',
	);

	/**
	 * No terms are seeded in v3. The type dropdown is driven by
	 * MBS_Taxonomy_Collection::get_types() alone.
	 */
	const TERMS = array();

	/**
	 * Run the seeder only when the stored version is behind SEEDED_VERSION.
	 */
	/**
	 * Register the init p20 hook for collection seeding.
	 * Moved from MBS_Plugin::load_post_types_and_taxonomies() — REFACTOR-PLAN-ARCH-001 Batch C.
	 */
	public static function register_hooks(): void {
		add_action( 'init', array( __CLASS__, 'maybe_seed' ), 20 );
	}

	public static function maybe_seed(): void {
		if ( get_option( self::SEEDED_OPTION ) === self::SEEDED_VERSION ) {
			return;
		}
		self::seed();
	}

	/**
	 * Remove legacy v2 terms (if unused), then record the new version.
	 * No new terms are inserted in v3.
	 */
	public static function seed(): void {
		self::remove_legacy_terms();
		update_option( self::SEEDED_OPTION, self::SEEDED_VERSION, false );
	}

	/**
	 * Delete each v2 term by name, but only if it has no books assigned.
	 * Terms with books are left untouched so no content is silently unlinked.
	 */
	private static function remove_legacy_terms(): void {
		foreach ( self::LEGACY_TERMS as $name ) {
			$term = get_term_by( 'name', $name, MBS_TAX_COLLECTION );
			if ( ! $term instanceof WP_Term ) {
				continue;
			}
			if ( (int) $term->count > 0 ) {
				// Term has books assigned — leave it in place.
				continue;
			}
			wp_delete_term( $term->term_id, MBS_TAX_COLLECTION );
		}
	}
}
