import { buildClaimUrl, createTaskClaimToken } from '../../claim/claim-service.js'
import type { TaskRow } from '../../../types/repository/rows.js'
import { getTaskClaimExpiresAt, isClaimExpired } from './task-context.js'

export async function ensureTaskClaimLink(task: TaskRow) {
  const tokenStatus = String(task?.primary_claim_token_status || '').trim()
  const token = String(task?.primary_claim_token || task?.claim_token || '').trim()
  const expiredAt = getTaskClaimExpiresAt(task)

  if (tokenStatus === 'active' && token && !isClaimExpired(expiredAt)) {
    return {
      token,
      expiredAt,
      claimUrl: buildClaimUrl(token),
    }
  }

  const claimToken = await createTaskClaimToken(task.id)
  return {
    token: claimToken.token,
    expiredAt: claimToken.expired_at,
    claimUrl: claimToken.claimUrl,
  }
}
