import {db} from '@db/instance';
import {reactions} from '@db/schema';
import {eq, inArray} from 'drizzle-orm';

import {InsertReaction} from '../interfaces';

export const setReactionsForMessage = async (
  messageId: string,
  values: InsertReaction[],
) => {
  await db.instance.transaction(async tx => {
    await tx.delete(reactions).where(eq(reactions.message_id, messageId));
    if (values.length > 0) {
      await tx.insert(reactions).values(values).onConflictDoNothing();
    }
  });
};

// Set reactions for multiple messages in a batch
export const setReactionsForMessageBatch = async (values: InsertReaction[]) => {
  if (!values.length) {
    return;
  }

  const messageIdsSet = new Set<string>();
  values.forEach(v => messageIdsSet.add(v.message_id));

  await db.instance.transaction(async tx => {
    await tx
      .delete(reactions)
      .where(inArray(reactions.message_id, [...messageIdsSet]));
    await tx.insert(reactions).values(values).onConflictDoNothing();
  });
};
