// @ts-nocheck
import mariadb from "mariadb";
import { assertReadOnlySql } from "../lib/sql-readonly.ts";

let pool;

export function isMariaDbConfigured(config) {
  return config.database?.driver === "mariadb";
}

export async function testMariaDbConnection(database) {
  const connection = await mariadb.createConnection({
    host: database.host,
    port: Number(database.port),
    database: database.name,
    user: database.user,
    password: database.password,
    bigIntAsNumber: true,
  });
  try {
    const rows = await connection.query("SELECT VERSION() AS version");
    return { connected: true, version: rows[0]?.version || "MariaDB" };
  } finally {
    await connection.end();
  }
}

export async function queryMariaDb(config, sql) {
  assertReadOnlySql(sql);
  const connection = await getPool(config).getConnection();
  try {
    const rows = await connection.query(sql);
    return { configured: true, items: normalizeRows(rows) };
  } finally {
    connection.release();
  }
}

export async function executeMariaDbWrite(config, sql) {
  if (config.database.mode !== "local") {
    throw new Error("MariaDB writes are blocked outside Local DB mode.");
  }
  if (!config.database.allowLocalWrites) {
    throw new Error("Local MariaDB writes are disabled. Enable local database writes in Settings first.");
  }

  const connection = await getPool(config).getConnection();
  try {
    const result = await connection.query(sql);
    return {
      configured: true,
      items: [],
      affectedRows: result.affectedRows ?? 0,
      insertId: result.insertId ?? 0,
    };
  } finally {
    connection.release();
  }
}

function getPool(config) {
  if (!pool) {
    pool = mariadb.createPool({
      host: config.database.host,
      port: config.database.port,
      database: config.database.name,
      user: config.database.user,
      password: config.database.password,
      connectionLimit: config.database.connectionLimit,
      bigIntAsNumber: true,
    });
  }
  return pool;
}

function normalizeRows(rows) {
  return Array.isArray(rows) ? rows.filter((row) => row && typeof row === "object" && !("meta" in row)) : [];
}
