<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-0.php
 *
 * MBS_Migration_4_0 -- Content Warning list revision (F-019 v2)
 *
 * Retires three deprecated seeded terms and renames one:
 *   - Delete: Abuse, Death of a Pet, Profanity
 *   - Rename: Substance Abuse -> Substance Abuse / Addiction
 *
 * Does not touch terms added by admins beyond those exact names.
 * Idempotent: each operation checks existence before acting.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

/**
 * Class MBS_Migration_4_0
 *
 * Retire old content warning terms and rename Substance Abuse.
 *
 * @implements MBS_Migration
 */
class MBS_Migration_4_0 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * {@inheritdoc}
	 *
	 * @return string
	 */
	public function version(): string {
		return '4.0';
	}

	/**
	 * {@inheritdoc}
	 *
	 * Delete retired terms from mbs_content_warning; rename Substance Abuse.
	 * Books assigned the deleted terms lose those assignments (expected).
	 * Books assigned Substance Abuse retain the assignment under the new name.
	 *
	 * @return void
	 */
	public function up(): void {
		// Terms to delete outright.
		$to_delete = array( 'Abuse', 'Death of a Pet', 'Profanity' );
		foreach ( $to_delete as $name ) {
			$term = get_term_by( 'name', $name, MBS_TAX_CONTENT_WARNING );
			if ( $term instanceof WP_Term ) {
				wp_delete_term( $term->term_id, MBS_TAX_CONTENT_WARNING );
			}
		}

		// Rename: Substance Abuse -> Substance Abuse / Addiction.
		$old_name = 'Substance Abuse';
		$new_name = 'Substance Abuse / Addiction';
		$term = get_term_by( 'name', $old_name, MBS_TAX_CONTENT_WARNING );
		if ( $term instanceof WP_Term && $term->name !== $new_name ) {
			wp_update_term(
				$term->term_id,
				MBS_TAX_CONTENT_WARNING,
				array( 'name' => $new_name )
			);
		}
	}
}
