<?php
/**
 * Database — Legacy compatibility shim.
 *
 * DEPRECATED since v6.5.0
 * ─────────────────────────────────────────────────────────────────────────────
 * All table CREATE TABLE statements have been moved into each module's own
 * schema class (implements ModuleSchemaInterface) and are installed by
 * DatabaseInstaller via the DatabaseTablesModule registry.
 *
 * This class is kept only because third-party code may reference
 * Database::table() or Database::get_table_names(). Both methods now delegate
 * to DatabaseSchema so there is a single source of truth.
 *
 * Database::create_tables() is a no-op — table creation is handled entirely by
 * DatabaseInstaller → module schemas → AbstractModuleSchema::install().
 *
 * @package    UltraguardPro\core
 * @deprecated 6.5.0  Use DatabaseSchema for name resolution.
 *                    Use module SchemaInterface classes for DDL.
 */

namespace UltraguardPro\core;

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange -- Legacy database compatibility shim intentionally performs low-level DB lookups and install-time table delegation.

class Database {

    /**
     * @deprecated 6.5.0  No-op — table creation is handled by module schemas.
     * @return bool  Always true.
     */
    public static function create_tables(): bool {
        // All tables are created via AbstractModuleSchema::install() in
        // DatabaseInstaller::run_upgrade(). Nothing to do here.
        return true;
    }

    /**
     * Drop all plugin tables. Used only on uninstall.
     *
     * @return bool
     */
    public static function drop_tables(): bool {
        global $wpdb;
        $success = true;
        $tables  = array_unique( array_values( self::get_table_names() ) );

        foreach ( $tables as $name ) {
            $safe_name = esc_sql( $name );
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $result = $wpdb->query( "DROP TABLE IF EXISTS `{$safe_name}`" );  // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name comes from the plugin's internal schema registry.
            if ( false === $result ) {
                \UltraguardPro\core\Logger::error( "Failed to drop table [{$name}]" );
                $success = false;
            }
        }

        return $success;
    }

    /**
     * Full prefixed table name for a given key.
     * Delegates to DatabaseSchema.
     *
     * @param  string $key  e.g. 'scan_results', 'firewall_rules'
     * @return string
     */
    public static function table( string $key ): string {
        if ( DatabaseSchema::get_table_name( $key ) ) {
            return DatabaseSchema::get_table_name( $key );
        }

        if ( str_starts_with( $key, 'ultraguard_' ) ) {
            return $GLOBALS['wpdb']->prefix . $key;
        }

        return $GLOBALS['wpdb']->prefix . 'ultraguard_' . $key;
    }

    /**
     * All known prefixed table names.
     * Delegates to DatabaseSchema.
     *
     * @return array<string, string>
     */
    public static function get_table_names(): array {
        return DatabaseSchema::get_table_names();
    }

    /**
     * Check which tables exist in the database.
     *
     * @return array{ all_exist: bool, tables: array<string, bool> }
     */
    public static function check_tables_exist(): array {
        global $wpdb;
        $results = [];

        // Use only short-key aliases discovered from the live schema map to avoid
        // duplicate checks for prefixed and unprefixed full table names.
        $known_short_keys = [];
        foreach ( DatabaseSchema::get_table_names() as $key => $full_name ) {
            if ( isset( $wpdb->prefix ) && $full_name === ( $wpdb->prefix . 'ultraguard_' . $key ) ) {
                $known_short_keys[] = $key;
            }
        }
        sort( $known_short_keys );

        foreach ( $known_short_keys as $key ) {
            $name = DatabaseSchema::get_table_name( $key );
            if ( $name ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $results[ $key ] = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- query uses prepare(); table name is supplied as a value placeholder.
            }
        }

        return [
            'all_exist' => ! in_array( false, $results, true ),
            'tables'    => $results,
        ];
    }
}
