import { runtimeConfig } from '../../config/runtime.js'
import { createClaimToken } from '../../repositories/claim-token-repo.js'
import { addHours, nowIso } from '../../utils/time.js'
import { randomToken } from '../../utils/random.js'

type TaskClaimToken = NonNullable<Awaited<ReturnType<typeof createClaimToken>>> & {
  claimUrl: string
}

export async function createTaskClaimToken(taskId: number | string): Promise<TaskClaimToken> {
  const createdAt = nowIso()
  const expiredAt = addHours(createdAt, Number(runtimeConfig.orders.tokenTtlHours || 24))
  const token = await createClaimToken({
    taskId: Number(taskId),
    token: randomToken(24),
    status: 'active',
    expiredAt,
    usedAt: null,
    maxUseCount: 1,
    usedCount: 0,
    createdAt,
    updatedAt: createdAt,
  })

  if (!token) {
    throw new Error('领取 token 创建失败')
  }

  return {
    ...token,
    claimUrl: buildClaimUrl(token.token),
  }
}

export function buildClaimUrl(token: string): string {
  const baseUrl = String(runtimeConfig.orders.claimBaseUrl || '').trim()
  return baseUrl ? `${baseUrl.replace(/\/+$/, '')}/${token}` : token
}
