/* eslint-disable react-hooks/rules-of-hooks */
// NOTE: add next line to keep sqlite3 in the bundle
import 'sqlite3';

import { join } from 'path';

import CLS from 'cls-hooked';
import { Sequelize } from 'sequelize';

import env, { sequelizeOptionsPoolIdle, sequelizeOptionsPoolMax, sequelizeOptionsPoolMin } from '../libs/env';

const namespace = CLS.createNamespace('payment-kit');

Sequelize.useCLS(namespace);

// eslint-disable-next-line import/prefer-default-export
export const sequelize = new Sequelize({
  dialect: 'sqlite',
  logging: process.env.SQL_LOG === '1',
  benchmark: process.env.SQL_LOG === '1' && process.env.SQL_BENCHMARK === '1',
  storage: join(env.dataDir, 'payment-kit.db'),
  pool: {
    min: sequelizeOptionsPoolMin,
    max: sequelizeOptionsPoolMax,
    idle: sequelizeOptionsPoolIdle,
  },
});

// SQLite PRAGMAs — run once at startup on the single reused connection.
// Note: SQLite in Sequelize reuses a cached connection (connection-manager.js:43-44),
// so these fire-and-forget calls reliably apply to all subsequent queries.
sequelize.query('PRAGMA journal_mode = WAL');
sequelize.query('PRAGMA synchronous = NORMAL');
sequelize.query('PRAGMA journal_size_limit = 67108864');
sequelize.query('PRAGMA busy_timeout = 5000');
sequelize.query('PRAGMA cache_size = -16000'); // 16MB page cache (default ~2MB)
