import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import { ForbiddenError } from "../lib/errors.generated";

export interface ResetNotificationPreferencesInput {
  userId: string;
}

/**
 * Hard-deletes all of the caller's NotificationPreference rows in one statement, restoring default opt-in. Self-service only; idempotent.
 */
export async function run(
  db: Transaction,
  input: ResetNotificationPreferencesInput,
  ctx: CommandContext,
) {
  const { userId } = input;

  if (ctx.actorId !== userId) {
    return err(new ForbiddenError(userId));
  }

  // Hard-delete every preference row for the calling user.
  // Idempotent: no rows = no-op.
  const deletedPreferences = await db
    .deleteFrom("NotificationPreference")
    .where("userId", "=", userId)
    .returningAll()
    .execute();

  return ok({ deletedCount: deletedPreferences.length });
}
