import type { Querier } from '@platform-modules/db'
import { and, eq, gte, sql } from 'drizzle-orm'

import { type PressZoneSchema, walletBalances } from '../schema.js'

type PressZoneQuerier = Querier<PressZoneSchema>

export function periodKey(account: string, plugin: string, period: string): string {
  return `${account}:${plugin}:${period}`
}

export async function seedPeriodWallet(
  db: PressZoneQuerier,
  key: string,
  allocation: bigint,
): Promise<void> {
  if (allocation < 0n) {
    throw new Error('seedPeriodWallet: allocation must be non-negative')
  }

  await db
    .insert(walletBalances)
    .values({
      ownerId: key,
      balance: allocation,
      updatedAt: new Date(),
    })
    .onConflictDoUpdate({
      target: walletBalances.ownerId,
      set: {
        balance: allocation,
        updatedAt: new Date(),
      },
    })
}

export async function debitCredits(
  db: PressZoneQuerier,
  key: string,
  amount: bigint,
): Promise<{ ok: boolean }> {
  if (amount <= 0n) {
    throw new Error('debitCredits: amount must be positive')
  }

  const updated = await db
    .update(walletBalances)
    .set({
      balance: sql`${walletBalances.balance} - ${amount}`,
      updatedAt: new Date(),
    })
    .where(and(eq(walletBalances.ownerId, key), gte(walletBalances.balance, amount)))
    .returning({ ownerId: walletBalances.ownerId })

  return { ok: updated.length > 0 }
}
