import { parseTaskContext as parseTaskContextValue } from '../../../utils/task-json.js'
import type { TaskRow } from '../../../types/repository/rows.js'
import type { JsonObject } from '../../../types/json.js'

export function normalizeActor(actor: unknown) {
  if (!actor || typeof actor !== 'object') {
    return null
  }

  const current = actor as JsonObject
  const source = String(current.source || '').trim()
  const userId = Number(current.userId || 0) || 0
  const username = String(current.username || '').trim()
  const role = String(current.role || '').trim()

  if (!source && !userId && !username && !role) {
    return null
  }

  return {
    source,
    userId,
    username,
    role,
  }
}

export function parseTaskContext(task: Partial<TaskRow> | null | undefined) {
  return parseTaskContextValue(task)
}

export function getTaskClaimExpiresAt(task: Partial<TaskRow> | null | undefined) {
  return task?.claim_expires_at || task?.primary_claim_expires_at || null
}

export function isClaimExpired(expiredAt: unknown) {
  if (!expiredAt) {
    return false
  }

  const timestamp = new Date(
    expiredAt instanceof Date ? expiredAt : String(expiredAt || ''),
  ).getTime()
  return Number.isFinite(timestamp) && timestamp <= Date.now()
}
