import postgres from "postgres";
import { Context } from "../context.js";
import { ExtractTablesWithRelations } from "drizzle-orm";
import { PgTransaction, PgTransactionConfig } from "drizzle-orm/pg-core";
import { PostgresJsQueryResultHKT, drizzle } from "drizzle-orm/postgres-js";

export namespace Database {
  const { DATABASE_URL } = process.env;
  if (!DATABASE_URL) {
    throw new Error("DATABASE_URL is not set");
  }

  const sql = postgres(DATABASE_URL, {
    max: 20,
    idle_timeout: 60,
  });

  const client = drizzle(sql);

  export type Transaction = PgTransaction<
    PostgresJsQueryResultHKT,
    Record<string, never>,
    ExtractTablesWithRelations<Record<string, never>>
  >;

  export type TxOrDb = Transaction | typeof client;

  const TransactionContext = Context.create<{
    tx: TxOrDb;
    effects: (() => void | Promise<void>)[];
  }>();

  export async function use<T>(callback: (trx: TxOrDb) => Promise<T>) {
    try {
      const { tx } = TransactionContext.use();
      return tx.transaction(callback);
    } catch (err) {
      if (err instanceof Context.NotFound) {
        const effects: (() => void | Promise<void>)[] = [];
        const result = await TransactionContext.provide(
          {
            effects,
            tx: client,
          },
          () => callback(client),
        );
        await Promise.all(effects.map((x) => x()));
        return result;
      }
      throw err;
    }
  }

  export async function fn<Input, T>(
    callback: (input: Input, trx: TxOrDb) => Promise<T>,
  ) {
    return (input: Input) => use(async (tx) => callback(input, tx));
  }

  export async function effect(effect: () => any | Promise<any>) {
    try {
      const { effects } = TransactionContext.use();
      effects.push(effect);
    } catch {
      await effect();
    }
  }

  export async function transaction<T>(
    callback: (tx: TxOrDb) => Promise<T>,
    config?: PgTransactionConfig,
  ) {
    try {
      const { tx } = TransactionContext.use();
      return callback(tx);
    } catch (err) {
      if (err instanceof Context.NotFound) {
        const effects: (() => void | Promise<void>)[] = [];
        const result = await client.transaction(async (tx) => {
          return TransactionContext.provide({ tx, effects }, () =>
            callback(tx),
          );
        }, config);
        await Promise.all(effects.map((x) => x()));
        return result;
      }
      throw err;
    }
  }
}
