<?php

namespace HelpGent\Database\Migrations;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\BackgroundProcessors\BackgroundProcessor;
use HelpGent\WpMVC\Contracts\Migration as MigrationBase;
use Exception;

abstract class Migration implements MigrationBase {
    protected $migration_version = '';

    protected bool $run_task_async = false;

    protected bool $clean_up_data_after_migration = false;

    public function more_than_version() {
        return $this->migration_version;
    }

    protected function before_start_migration(): void {
        // Do anything which needs to be done before starting migration
    }

    protected function skip_migration(): bool {
        return false;
    }

    public function execute(): bool {
        if ( $this->skip_migration() ) {
            return true;
        }

        /**
         * @var BackgroundProcessor $background_processor
         */
        $background_processor = new BackgroundProcessor( "db_migration_v{$this->migration_version}", $this->run_task_async );
        $background_process   = $background_processor->get_background_process();

        if ( $background_process->is_finished() ) {
            return $this->after_finish_migration();
        }

        if ( $background_process->is_active() ) {
            if ( ! $background_process->is_processing() ) {
                $background_process->dispatch();
            }

            add_filter( 'helpgent_show_admin_notice_for_migration_status', '__return_true', 15 );
            return false;
        }

        if ( ! $background_process->is_active() ) {
            try {
                $this->before_start_migration();
                $background_processor->run( $this->get_migration_tasks() );
            } catch ( Exception $e ) {
            }
        }

        return false;
    }

    public function after_finish_migration(): bool {
        if ( $this->clean_up_data_after_migration ) {
            return $this->maybe_clean_up_data();
        }

        return true;
    }

    public function maybe_clean_up_data(): bool {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $clean_up_data = isset( $_GET['helpgent-clean-up-db-data'] ) && ! empty( sanitize_text_field( wp_unslash( $_GET['helpgent-clean-up-db-data'] ) ) );

        if ( $clean_up_data ) {
            $this->clean_up_data();
            return true;
        }

        add_filter( 'helpgent_show_admin_notice_for_deleting_old_db_data', '__return_true', 15 );

        return false;
    }

    abstract protected function get_migration_tasks(): array;

    protected function clean_up_data(): void {}
}