<?php

namespace EasyLinkAutomations\Database;

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

/**
 * Thin static wrapper around $wpdb.
 */
final class Connection
{
    /**
     * Execute a query and return the number of affected rows (or false on error).
     */
    public static function query(string $sql): int|bool
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- DDL migration queries; callers pass schema SQL with no user input.
        return $wpdb->query($sql);
    }

    /**
     * Get multiple rows as an array of objects or arrays.
     */
    public static function getResults(string $sql, string $output = OBJECT): array
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- DDL migration queries; callers pass schema SQL with no user input.
        return $wpdb->get_results($sql, $output) ?? [];
    }

    /**
     * Get a single value from the first column of the first row.
     */
    public static function getVar(string $sql): mixed
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- DDL migration queries; callers pass schema SQL with no user input.
        return $wpdb->get_var($sql);
    }

    /**
     * Prepare a SQL query with placeholders via $wpdb->prepare().
     */
    public static function prepare(string $query, mixed ...$args): string
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- This method IS the prepare wrapper; callers pass the format string and values.
        return $wpdb->prepare($query, ...$args);
    }

    /**
     * Return the WordPress table prefix ($wpdb->prefix).
     */
    public static function wpPrefix(): string
    {
        global $wpdb;

        return $wpdb->prefix;
    }

    /**
     * Get a single row as an object or array.
     */
    public static function getRow(string $sql, string $output = OBJECT): mixed
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- DDL migration queries; callers pass schema SQL with no user input.
        return $wpdb->get_row($sql, $output);
    }
}
