import { Pool } from "pg";
import {
  DeduplicateJoinsPlugin,
  Kysely,
  PostgresDialect,
  type LogEvent,
  type Transaction,
} from "kysely";
import { env } from "~/env.mjs";
import type Database from "~/schemas/Database";
import type PublicSchema from "~/schemas/public/PublicSchema";
/**
 * The database connection pool.
 */
const pool = new Pool({
  host: env.PGHOST,
  user: env.POSTGRES_USER,
  database: env.POSTGRES_DB,
  password: env.POSTGRES_PASSWORD,
  port: Number.parseInt(env.PGPORT),
  max: 10,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

type Db = typeof db;

type Trx = Transaction<PublicSchema>;

export type Querier = Db | Trx;
/**
 * The database instance.
 */
export const db = new Kysely<Database>({
  dialect: new PostgresDialect({
    pool: pool,
  }),
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  log: (event) => {
    //DbLogger(event);
  },

  //plugins: [new SerializePlugin()]
  //plugins: [new CamelCasePlugin()],
  plugins: [new DeduplicateJoinsPlugin()],
});

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const DbLogger = (event: LogEvent) => {
  if (event.level === "query") {
    console.log("\x1b[33mquery:\x1b[0m", event.query.sql);
    console.log("\x1b[36mparams:\x1b[0m", event.query.parameters);
    console.log("\x1b[32mtaken:\x1b[0m", event.queryDurationMillis, "ms");
  }
  if (event.level === "error") {
    console.error("\x1b[33mquery:\x1b[0m", event.query.sql);
    console.error("\x1b[36mparams:\x1b[0m", event.query.parameters);
    console.error("\x1b[31merror:\x1b[0m", event.error);
  }
};
