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))
}

export const WORK_ORDER_SHARE_SELECT = `
  SELECT
    wos.*,
    wu.username AS worker_username,
    wu.display_name AS worker_display_name
  FROM work_order_shares wos
  LEFT JOIN worker_users wu ON wu.id = wos.worker_id
`

/** 校验单个拼单份额能否撤单，并返回母工单应回退到的状态。 */
export function resolveWorkOrderShareCancellationStatus(
  workOrderStatus: string,
  shareStatus: string,
): 'open' | null {
  // in_progress 用于解围历史问题单处置产生的"份额已提交、母单回到进行中"的卡死存量单
  if (!['open', 'pending_acceptance', 'in_progress'].includes(workOrderStatus)) return null
  if (!['joined', 'submitted'].includes(shareStatus)) return null
  return 'open'
}

/**
 * 校验母单级拼单撤单。退回大厅只影响尚未验收的份额；取消整单则不能存在已验收份额，
 * 否则必须经售后处理已结算的报酬和订单退款。
 */
export function resolveWorkOrderSharingCancellationPlan(
  workOrderStatus: string,
  shareStatuses: string[],
  action: 'return_to_hall' | 'cancel_order',
): {
  nextOrderStatus: 'open' | 'cancelled' | null
  cancellableShareCount: number
  acceptedShareCount: number
  failureReason:
    | 'work_order_not_cancellable'
    | 'no_cancellable_shares'
    | 'accepted_shares_present'
    | null
} {
  if (!['open', 'pending_acceptance', 'in_progress'].includes(workOrderStatus)) {
    return {
      nextOrderStatus: null,
      cancellableShareCount: 0,
      acceptedShareCount: 0,
      failureReason: 'work_order_not_cancellable',
    }
  }
  const cancellableShareCount = shareStatuses.filter((status) =>
    ['joined', 'submitted'].includes(status),
  ).length
  const acceptedShareCount = shareStatuses.filter((status) => status === 'accepted').length
  if (cancellableShareCount === 0) {
    return {
      nextOrderStatus: null,
      cancellableShareCount,
      acceptedShareCount,
      failureReason: 'no_cancellable_shares',
    }
  }
  if (action === 'cancel_order' && acceptedShareCount > 0) {
    return {
      nextOrderStatus: null,
      cancellableShareCount,
      acceptedShareCount,
      failureReason: 'accepted_shares_present',
    }
  }
  return {
    nextOrderStatus: action === 'return_to_hall' ? 'open' : 'cancelled',
    cancellableShareCount,
    acceptedShareCount,
    failureReason: null,
  }
}
