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 DeleteNotificationSubscriptionInput {
  userId: string;
  sourceType: string;
  sourceId: string;
}

/**
 * Hard-deletes the NotificationSubscription for a (userId, sourceType, sourceId) triple. Idempotent no-op when absent; self-service only.
 */
export async function run(
  db: Transaction,
  input: DeleteNotificationSubscriptionInput,
  ctx: CommandContext,
) {
  const { userId, sourceType, sourceId } = input;

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

  const existing = await db
    .selectFrom("NotificationSubscription")
    .selectAll()
    .where("userId", "=", userId)
    .where("sourceType", "=", sourceType)
    .where("sourceId", "=", sourceId)
    .forUpdate()
    .executeTakeFirst();

  // Idempotent: missing row is a no-op success.
  if (!existing) {
    return ok({ deleted: false });
  }

  await db
    .deleteFrom("NotificationSubscription")
    .where("userId", "=", userId)
    .where("sourceType", "=", sourceType)
    .where("sourceId", "=", sourceId)
    .execute();

  return ok({ deleted: true });
}
