<?php

class DatabaseHelper
{
    public const PGSQL_UNIQUE_VIOLATION = '23505';

    /**
     * Convert array to PostgreSQL array
     * @param array $tags
     * @return string
     */
    public static function toPgArray(array $items): string
    {
        $escapedItems = array_map(function ($item): string {
            $escaped = str_replace(['\\', '"'], ['\\\\', '\\"'], $item);
            return '"' . $escaped . '"';
        }, $items);

        return '{' . implode(',', $escapedItems) . '}';
    }

    public static function transformUniqueViolationToResponseException(PDOException $exception, string $uniqueViolationMessage)
    {
        if ($exception->getCode() === self::PGSQL_UNIQUE_VIOLATION) {
            throw new ResponseException($uniqueViolationMessage, Response::CONFLICT);
        } else {
            throw $exception;
        }
    }

    /**
     * Quote a value for safe use in SQL queries
     * Uses PDO::quote to properly escape and quote values for SQL
     * This function should be used when we call Query API
     * to sanitize input.
     */
    public static function quote($value): bool|string
    {
        $pdo = CfSettings::getInstance()->getConnection();
        return $pdo->quote($value);
    }
}
