<?php
namespace AIPT\Core\Database;

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

/**
 * Cleans orphaned records when parent entities (products, jobs) are deleted.
 *
 * @since 2.6.0
 */
class OrphanCleaner {

    /**
     * Register all cleanup hooks.
     */
    public static function register(): void {

        add_action('before_delete_post', [self::class, 'on_product_deleted'], 10, 2);

    }

    /**
     * Clean related records when a product post is permanently deleted.
     *
     * @param int      $post_id Post ID being deleted.
     * @param \WP_Post $post    Post object.
     */
    public static function on_product_deleted(int $post_id, $post): void {

        if (!$post || $post->post_type !== 'product') {
            return;
        }

        global $wpdb;
        $product_id = $post_id;

        $table = $wpdb->prefix . 'aipt_bulk_generator_history';

        $wpdb->delete($table, ['product_id' => $product_id], ['%d']);

        $table = $wpdb->prefix . 'aipt_draft_content';

        $wpdb->delete($table, ['product_id' => $product_id], ['%d']);

        $table = $wpdb->prefix . 'aipt_job_products';

        $wpdb->delete($table, ['product_id' => $product_id], ['%d']);

        $table = $wpdb->prefix . 'aipt_seo_meta_history';

        $wpdb->delete($table, ['product_id' => $product_id], ['%d']);
    }

    /**
     * Clean related records when an automation job is deleted.
     *
     * Call this from wherever jobs are deleted (AutomationJobsController or AutomationJobManager).
     *
     * @param int $job_id The job ID being deleted.
     */
    public static function on_job_deleted(int $job_id): void {
        global $wpdb;

        $table = $wpdb->prefix . 'aipt_job_products';

        $wpdb->delete($table, ['job_id' => $job_id], ['%d']);

        $table = $wpdb->prefix . 'aipt_job_logs';

        $wpdb->delete($table, ['job_id' => $job_id], ['%d']);

        $table = $wpdb->prefix . 'aipt_draft_content';

        $wpdb->delete($table, ['job_id' => $job_id], ['%d']);
    }
}
