import { and, eq, inArray } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import { deals, liveNotifications } from '../schema.js';
import type { NotificationInsert } from '../schema.js';

export async function setTranslationStatus(
  db: DrizzleClient,
  dealId: string,
  translationStatus: typeof deals.$inferInsert.translationStatus,
): Promise<void> {
  await db.update(deals).set({ translationStatus }).where(eq(deals.id, dealId));
}

export async function markDealsSlaAlerted(db: DrizzleClient, dealIds: string[]): Promise<void> {
  if (dealIds.length === 0) return;
  await db.update(deals).set({ slaAlertedAt: new Date() }).where(inArray(deals.id, dealIds));
}

export async function setDealPendingApprovalIfUnderReview(
  db: DrizzleClient,
  dealId: string,
): Promise<boolean> {
  const updated = await db
    .update(deals)
    .set({ dealState: 'PENDING_APPROVAL' })
    .where(and(eq(deals.id, dealId), eq(deals.dealState, 'UNDER_REVIEW')))
    .returning({ id: deals.id });
  return updated.length > 0;
}

export async function insertLiveNotifications(
  db: DrizzleClient,
  values: NotificationInsert[],
): Promise<Array<{ id: string; userId: string }>> {
  if (values.length === 0) return [];
  return db
    .insert(liveNotifications)
    .values(values)
    .returning({ id: liveNotifications.id, userId: liveNotifications.userId });
}
