// apps/web/src/server/db/queries/chat-thread-participants.ts
import { and, eq } from 'drizzle-orm';
import type { DrizzleClient } from '@/server/db/client.js';
import {
  chatThreadParticipants,
  type ChatThreadParticipantRow,
} from '@/server/db/schema.js';

export async function addParticipants(
  db: DrizzleClient,
  threadId: string,
  userIds: string[],
): Promise<void> {
  if (userIds.length === 0) return;
  await db
    .insert(chatThreadParticipants)
    .values(userIds.map((userId) => ({ threadId, userId })))
    .onConflictDoNothing();
}

export async function isParticipant(
  db: DrizzleClient,
  threadId: string,
  userId: string,
): Promise<boolean> {
  const [row] = await db
    .select({ threadId: chatThreadParticipants.threadId })
    .from(chatThreadParticipants)
    .where(
      and(
        eq(chatThreadParticipants.threadId, threadId),
        eq(chatThreadParticipants.userId, userId),
      ),
    )
    .limit(1);
  return !!row;
}

export async function listParticipants(
  db: DrizzleClient,
  threadId: string,
): Promise<ChatThreadParticipantRow[]> {
  return db
    .select()
    .from(chatThreadParticipants)
    .where(eq(chatThreadParticipants.threadId, threadId));
}

export async function setLastRead(
  db: DrizzleClient,
  threadId: string,
  userId: string,
  at: Date,
): Promise<void> {
  await db
    .update(chatThreadParticipants)
    .set({ lastReadAt: at })
    .where(
      and(
        eq(chatThreadParticipants.threadId, threadId),
        eq(chatThreadParticipants.userId, userId),
      ),
    );
}
