import { runtimeConfig } from '../../config/runtime.js'
import { createClaimToken } from '../../repositories/claim-token-repo.js'
import { createHttpError } from '../../utils/http.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 = resolveClaimTokenExpiration(createdAt, runtimeConfig.orders.tokenTtlHours)
  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 createHttpError('领取 token 创建失败', {
      statusCode: 500,
      errorCode: 'claim_token_create_failed',
    })
  }

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

/** 0 表示长期有效；正整数保留为可选的限时领取策略。 */
export function resolveClaimTokenExpiration(
  createdAt: string,
  tokenTtlHours: unknown,
): string | null {
  const ttlHours = Number(tokenTtlHours)
  return Number.isFinite(ttlHours) && ttlHours > 0 ? addHours(createdAt, ttlHours) : null
}

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