export const TASK_STATUS = {
  PENDING_PAYMENT: 'pending_payment',
  PAID: 'paid',
  LINK_GENERATED: 'link_generated',
  CLAIMED: 'claimed',
  PENDING_BINDING_PREPARE: 'pending_binding_prepare',
  WAITING_BINDING: 'waiting_binding',
  ROLE_CONFIRMED: 'role_confirmed',
  REDEEMING: 'redeeming',
  DISPATCHED_PENDING_RETURN: 'dispatched_pending_return',
  COMPLETED: 'completed',
  REDEEMED: 'redeemed',
  RETRY_PENDING: 'retry_pending',
  MANUAL_REVIEW: 'manual_review',
  FAILED: 'failed',
  EXPIRED: 'expired',
  CLOSED: 'closed',
} as const

export type KnownTaskStatus = (typeof TASK_STATUS)[keyof typeof TASK_STATUS]
export type TaskStatus = KnownTaskStatus | (string & {})

const CLAIM_INACTIVE_STATUSES = new Set<TaskStatus>([
  TASK_STATUS.COMPLETED,
  TASK_STATUS.REDEEMED,
  TASK_STATUS.MANUAL_REVIEW,
  TASK_STATUS.FAILED,
  TASK_STATUS.EXPIRED,
  TASK_STATUS.CLOSED,
])

const KUAISHOU_CLOUD_RESULT_STATUSES = new Set<TaskStatus>([
  TASK_STATUS.DISPATCHED_PENDING_RETURN,
  TASK_STATUS.COMPLETED,
  TASK_STATUS.REDEEMED,
  TASK_STATUS.MANUAL_REVIEW,
  TASK_STATUS.FAILED,
])

export function normalizeTaskStatus(value: unknown): TaskStatus {
  return String(value || '').trim() as TaskStatus
}

export function isClaimInactiveTaskStatus(status: unknown): boolean {
  return CLAIM_INACTIVE_STATUSES.has(normalizeTaskStatus(status))
}

export function isKuaishouCloudRoleConfirmedStatus(status: unknown): boolean {
  return normalizeTaskStatus(status) === TASK_STATUS.ROLE_CONFIRMED
}

export function isKuaishouCloudCompletedStatus(status: unknown): boolean {
  const normalized = normalizeTaskStatus(status)
  return normalized === TASK_STATUS.COMPLETED || normalized === TASK_STATUS.REDEEMED
}

export function hasKuaishouCloudRedeemResultStatus(status: unknown): boolean {
  return KUAISHOU_CLOUD_RESULT_STATUSES.has(normalizeTaskStatus(status))
}
