import knex from 'knex';
import { env } from '../config/env.js';

export const db = knex({
  client: env.DB_CLIENT,
  connection: {
    host: env.DB_HOST,
    port: env.DB_PORT,
    database: env.DB_NAME,
    user: env.DB_USER,
    password: env.DB_PASSWORD,
    ssl: env.DB_SSL ? { rejectUnauthorized: false } : false,
  },
  pool: {
    min: 0,
    max: 10,
    afterCreate(connection: any, done: (error: Error | null, connection: any) => void) {
      const clientName = String(env.DB_CLIENT ?? '').toLowerCase();

      if (clientName === 'pg' || clientName === 'postgres' || clientName === 'postgresql') {
        connection.query(`SET TIME ZONE '${env.DB_TIME_ZONE}'`, (error: Error | null) => {
          done(error, connection);
        });
        return;
      }

      if (clientName === 'mysql' || clientName === 'mysql2') {
        connection.query('SET time_zone = "+09:00"', (error: Error | null) => {
          done(error, connection);
        });
        return;
      }

      done(null, connection);
    },
  },
});
