<?php
/**
 * Design system index table schema (PRD section 4.3).
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Index;

/**
 * Persists edge rows for the Bricks design system index.
 */
class IndexSchema
{
    public const SCHEMA_VERSION = 1;

    public static function tableName(): string
    {
        global $wpdb;

        return $wpdb->prefix . 'lolacore_bricks_index';
    }

    public static function tableExists(): bool
    {
        global $wpdb;

        $table = self::tableName();

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_var(
            $wpdb->prepare('SHOW TABLES LIKE %s', $table)
        ) === $table;
    }

    public static function create(): void
    {
        global $wpdb;

        if (!function_exists('dbDelta')) {
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        }

        $table   = self::tableName();
        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table} (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  ref_type varchar(20) NOT NULL,
  ref_id varchar(191) NOT NULL,
  post_id bigint(20) unsigned NOT NULL DEFAULT 0,
  area varchar(24) NOT NULL,
  element_id varchar(32) DEFAULT NULL,
  element_name varchar(64) DEFAULT NULL,
  PRIMARY KEY  (id),
  KEY idx_ref (ref_type, ref_id(64)),
  KEY idx_post (post_id),
  KEY idx_area (area)
) {$charset};";

        dbDelta($sql);

        update_option(
            'lolacore_bricks_index_state',
            [
                'schema_version' => self::SCHEMA_VERSION,
                'built_at'       => null,
                'class_stamp'    => null,
                'max_modified'   => null,
                'indexed_pages'  => 0,
                'total_pages'    => 0,
            ],
            false
        );
    }

    public static function drop(): void
    {
        global $wpdb;

        $table = self::tableName();

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name uses $wpdb->prefix plus a fixed suffix.
        $wpdb->query("DROP TABLE IF EXISTS {$table}");
    }
}
