import { and, eq, inArray, isNotNull, lt } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import { deals, order, pageLayoutPointers, refundIntent, translationJobs } from '../schema.js';

export async function expireSoldOutGold(db: DrizzleClient, now: Date): Promise<void> {
  await db
    .update(deals)
    .set({ soldOutGoldExpiresAt: null })
    .where(and(isNotNull(deals.soldOutGoldExpiresAt), lt(deals.soldOutGoldExpiresAt, now)));
}

export async function completeFulfilledOrder(
  db: DrizzleClient,
  orderId: string,
  now: Date,
): Promise<boolean> {
  const rows = await db
    .update(order)
    .set({ status: 'completed', updatedAt: now })
    .where(and(eq(order.id, orderId), eq(order.status, 'fulfilled')))
    .returning({ id: order.id });
  return rows.length > 0;
}

export async function failPendingRefundIntent(db: DrizzleClient, id: string): Promise<void> {
  await db
    .update(refundIntent)
    .set({ status: 'failed', updatedAt: new Date() })
    .where(and(eq(refundIntent.id, id), eq(refundIntent.status, 'pending')));
}

export async function publishLayoutPointer(
  db: DrizzleClient,
  page: string,
  liveVersionId: string,
): Promise<void> {
  await db
    .update(pageLayoutPointers)
    .set({ liveVersionId, scheduledVersionId: null, scheduledAt: null })
    .where(eq(pageLayoutPointers.page, page));
}

export async function reapRunningTranslationJobs(db: DrizzleClient): Promise<void> {
  await db
    .update(translationJobs)
    .set({ status: 'PENDING', startedAt: null })
    .where(
      and(
        eq(translationJobs.status, 'RUNNING'),
        lt(translationJobs.startedAt, new Date(Date.now() - 10 * 60 * 1000)),
      ),
    );
}

export async function expireDeals(db: DrizzleClient, now: Date): Promise<Array<{ id: string }>> {
  return db
    .update(deals)
    .set({ dealState: 'EXPIRED' })
    .where(
      and(
        inArray(deals.dealState, ['ACTIVE', 'PAUSED']),
        isNotNull(deals.windowEnd),
        lt(deals.windowEnd, now),
      ),
    )
    .returning({ id: deals.id });
}
