<?php
/**
 * File Path: includes/migrations/class-mbs-migration-3-3.php
 *
 * MBS_Migration_3_3 -- Session 98 -- Consolidate mbs_book_status into mbs_lifecycle_state
 *
 * One-time postmeta migration. For every book post that has a non-empty
 * mbs_book_status value AND an empty mbs_lifecycle_state, map the value to
 * the canonical mbs_lifecycle_state enum and write it. Then delete the
 * now-redundant mbs_book_status postmeta row.
 *
 * Value mapping:
 *   draft        -> draft
 *   coming_soon  -> coming_soon
 *   pre_order    -> preorder
 *   published    -> '' (empty = published is the lifecycle default)
 *   out_of_print -> out_of_print
 *   discontinued -> discontinued
 *   (empty)      -> no write; mbs_book_status deleted only
 *
 * @package MyBookShowroom
 * @since   3.3.0
 */

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

/**
 * Class MBS_Migration_3_3
 *
 * Migrate mbs_book_status postmeta to mbs_lifecycle_state.
 *
 * @implements MBS_Migration
 */
class MBS_Migration_3_3 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 '3.3';
	}

	/**
	 * {@inheritdoc}
	 *
	 * Idempotent: books that already have mbs_lifecycle_state set are skipped;
	 * mbs_book_status is deleted regardless so orphaned rows are cleaned up.
	 *
	 * @return void
	 */
	public function up(): void {
		$status_map = array(
			'draft'        => 'draft',
			'coming_soon'  => 'coming_soon',
			'pre_order'    => 'preorder',
			'published'    => '',
			'out_of_print' => 'out_of_print',
			'discontinued' => 'discontinued',
		);

		$query = new WP_Query(
			array(
				'post_type'      => MBS_POST_TYPE,
				'post_status'    => 'any',
				'posts_per_page' => -1,
				'fields'         => 'ids',
				'meta_query'     => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- standard WP query pattern; VIP rule does not apply to this plugin
					'relation' => 'AND',
					array(
						'key'     => 'mbs_book_status',
						'compare' => 'EXISTS',
					),
					array(
						'key'     => 'mbs_book_status',
						'value'   => '',
						'compare' => '!=',
					),
				),
			)
		);

		foreach ( $query->posts as $post_id ) {
			$book_status    = get_post_meta( $post_id, 'mbs_book_status',    true );
			$lifecycle_state = get_post_meta( $post_id, 'mbs_lifecycle_state', true );

			// Only write lifecycle_state when it is not already set.
			if ( '' === (string) $lifecycle_state && isset( $status_map[ $book_status ] ) ) {
				update_post_meta( $post_id, 'mbs_lifecycle_state', $status_map[ $book_status ] );
			}

			// Always clean up the retired meta key.
			delete_post_meta( $post_id, 'mbs_book_status' );
		}
	}
}
