import type { PoolClient } from 'pg'

import type { WorkerWalletRow } from './types.js'


export async function ensureWorkerWalletWithClient(
  client: PoolClient,
  workerId: number,
  now: string,
): Promise<void> {
  if (!workerId) return
  await client.query(
    `
      INSERT INTO worker_wallets (
        worker_id, available_amount, frozen_deposit_amount,
        total_credited_amount, total_settled_amount, created_at, updated_at
      ) VALUES ($1, 0, 0, 0, 0, $2, $3)
      ON CONFLICT (worker_id) DO NOTHING
    `,
    [workerId, now, now],
  )
}

export async function getWorkerWalletWithClient(
  client: PoolClient,
  workerId: number,
): Promise<WorkerWalletRow | null> {
  const result = await client.query<WorkerWalletRow>(
    'SELECT * FROM worker_wallets WHERE worker_id = $1 LIMIT 1 FOR UPDATE',
    [workerId],
  )
  return result.rows[0] || null
}

export function toJsonString(value: unknown): string {
  if (typeof value === 'string') return value
  return JSON.stringify(value ?? {})
}

export function toPositiveInteger(value: unknown, fallback: number): number {
  const parsed = Number(value ?? '')
  if (!Number.isFinite(parsed)) return fallback
  return Math.max(0, Math.round(parsed))
}
