<?php

namespace App\Support;

use Illuminate\Support\Facades\DB;

class SqliteCompat
{
    public static function statement(string $sql): bool
    {
        $connection = DB::connection();
        $driver = $connection->getDriverName();

        if ($driver !== 'sqlite') {
            return $connection->statement($sql);
        }

        $trimmed = ltrim($sql);
        if (stripos($trimmed, 'ALTER TABLE') === 0) {
            // SQLite cannot add primary keys or change auto_increment via ALTER.
            return true;
        }

        if (stripos($trimmed, 'CREATE TABLE') === 0) {
            $sql = self::normalizeCreateTable($sql);
        } else {
            $sql = self::normalizeGeneric($sql);
        }

        return $connection->statement($sql);
    }

    private static function normalizeCreateTable(string $sql): string
    {
        $sql = self::normalizeGeneric($sql);

        // Promote `id` column to PRIMARY KEY if not already.
        $sql = preg_replace(
            '/`id`\\s+integer\\s+NOT NULL/i',
            '`id` integer PRIMARY KEY NOT NULL',
            $sql,
            1
        );

        return $sql;
    }

    private static function normalizeGeneric(string $sql): string
    {
        // Remove engine/charset/collation.
        $sql = preg_replace('/\\)\\s*ENGINE=.*$/is', ')', $sql);
        $sql = preg_replace('/\\)\\s*DEFAULT CHARSET=.*$/is', ')', $sql);
        $sql = preg_replace('/\\)\\s*CHARSET=.*$/is', ')', $sql);
        $sql = preg_replace('/\\)\\s*COLLATE=.*$/is', ')', $sql);

        // Replace MySQL-specific types.
        $sql = preg_replace('/int\\(\\d+\\)\\s+unsigned/i', 'integer', $sql);
        $sql = preg_replace('/int\\(\\d+\\)/i', 'integer', $sql);
        $sql = preg_replace('/\\bint\\b/i', 'integer', $sql);
        $sql = preg_replace('/smallint\\(\\d+\\)/i', 'integer', $sql);
        $sql = preg_replace('/tinyint\\(\\d+\\)/i', 'integer', $sql);
        $sql = preg_replace('/decimal\\(\\d+\\s*,\\s*\\d+\\)/i', 'numeric', $sql);
        $sql = preg_replace('/enum\\s*\\([^\\)]*\\)/i', 'text', $sql);
        $sql = preg_replace('/\\bunsigned\\b/i', '', $sql);
        $sql = preg_replace('/\\s+COMMENT\\s+\'[^\']*\'/i', '', $sql);
        $sql = preg_replace('/\\s+ON\\s+UPDATE\\s+CURRENT_TIMESTAMP/i', '', $sql);
        $sql = preg_replace('/\\s+COLLATE\\s+\\w+/i', '', $sql);
        $sql = preg_replace('/\\s+CHARACTER\\s+SET\\s+\\w+/i', '', $sql);
        $sql = preg_replace('/set\\s*\\([^\\)]*\\)/i', 'text', $sql);

        return rtrim($sql, " \t\n\r\0\x0B;");
    }
}
