import { and, eq, inArray } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { enqueue } from "@/lib/jobs";

/** In-app notification + optional Slack fan-out (internal alerts). */
export async function notifyUser(ctx: Pick<Ctx, "db" | "workspace">, userId: string, kind: string, title: string, body?: string, link?: string) {
  await ctx.db.insert(schema.notifications).values({ workspaceId: ctx.workspace.id, userId, kind, title, body: body ?? null, link: link ?? null });
  await enqueue(ctx.db, "notify.slack", { workspaceId: ctx.workspace.id, title, body: body ?? "", link: link ?? "" }, { workspaceId: ctx.workspace.id, maxAttempts: 3 });
}

export async function notifyAdmins(ctx: Pick<Ctx, "db" | "workspace">, kind: string, title: string, body?: string, link?: string, roleKeys = ["workspace_admin", "marketing_manager"]) {
  const admins = await ctx.db.select({ userId: schema.memberships.userId }).from(schema.memberships).innerJoin(schema.roles, eq(schema.roles.id, schema.memberships.roleId))
    .where(and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.active, true), inArray(schema.roles.key, roleKeys)));
  const ids = [...new Set(admins.map((a) => a.userId))];
  if (ids.length) await ctx.db.insert(schema.notifications).values(ids.map((userId) => ({ workspaceId: ctx.workspace.id, userId, kind, title, body: body ?? null, link: link ?? null })));
  await enqueue(ctx.db, "notify.slack", { workspaceId: ctx.workspace.id, title, body: body ?? "", link: link ?? "" }, { workspaceId: ctx.workspace.id, maxAttempts: 3 });
}

/** Team-wide notification used by journey "notify team" actions. */
export async function notifyTeam(ctx: Pick<Ctx, "db" | "workspace">, title: string, body?: string, link?: string, userIds?: string[]) {
  if (userIds?.length) {
    await ctx.db.insert(schema.notifications).values(userIds.map((userId) => ({ workspaceId: ctx.workspace.id, userId, kind: "alert", title, body: body ?? null, link: link ?? null })));
    await enqueue(ctx.db, "notify.slack", { workspaceId: ctx.workspace.id, title, body: body ?? "", link: link ?? "" }, { workspaceId: ctx.workspace.id, maxAttempts: 3 });
  } else await notifyAdmins(ctx, "alert", title, body, link);
}
