import { Provider } from "@nestjs/common";
import { nodePostgresConnection } from "@slackwsh/data";
import PgBoss from "pg-boss";

export const PG_BOSS = "PG_BOSS";

export const QUEUES = [
  "notifications",
  "email",
  "sms",
  "unfurl",
  "search_index",
  "media",
  "webhooks",
  "retention",
  "exports",
  "analytics",
] as const;
export type QueueName = (typeof QUEUES)[number];

export const bossProvider: Provider = {
  provide: PG_BOSS,
  useFactory: async () => {
    const rawUrl =
      process.env.DATABASE_URL ?? "postgres://slackwsh_app:slackwsh_app@localhost:5432/slackwsh";
    // Must strip sslmode= from the URL: recent `pg` treats require as verify-full
    // and overwrites ssl: { rejectUnauthorized: false } when both are present.
    const boss = new PgBoss(nodePostgresConnection(rawUrl));
    await boss.start();
    for (const queue of QUEUES) {
      await boss.createQueue(queue);
    }
    return boss;
  },
};
