import { invalidateDashboardCache } from "../lib/cache.js";
import { logger } from "../lib/logger.js";
import { dispatchWebhooks } from "../lib/webhook-dispatcher.js";
import type { TRPCContext } from "../trpc.js";

function runProjectBackgroundEffect(
  effectName: string,
  execute: () => unknown,
  metadata: Record<string, unknown> = {},
): void {
  void Promise.resolve()
    .then(execute)
    .catch((error) => {
      logger.error(
        { err: error, effectName, ...metadata },
        "Project background side effect failed",
      );
    });
}

export type ProjectBackgroundEffects = {
  invalidateDashboardCacheInBackground: () => void;
  dispatchProjectWebhookInBackground: (
    db: TRPCContext["db"],
    event: string,
    payload: Record<string, unknown>,
  ) => void;
};

export function createProjectBackgroundEffects(): ProjectBackgroundEffects {
  return {
    invalidateDashboardCacheInBackground(): void {
      runProjectBackgroundEffect("invalidateDashboardCache", () => invalidateDashboardCache());
    },

    dispatchProjectWebhookInBackground(
      db: TRPCContext["db"],
      event: string,
      payload: Record<string, unknown>,
    ): void {
      runProjectBackgroundEffect(
        "dispatchWebhooks",
        () => dispatchWebhooks(db, event, payload),
        { event },
      );
    },
  };
}
