import type { WorkerUserRow } from '../../repositories/worker-platform/index.js'
import { createHttpError } from '../../utils/http.js'

export function assertWorkerLoginAllowed(worker: WorkerUserRow) {
  if (worker.status === 'active') return

  if (worker.status === 'rejected') {
    throw createHttpError('接单账号已被冻结，无法登录', {
      statusCode: 403,
      errorCode: 'worker_rejected',
    })
  }

  if (worker.status === 'pending_review') {
    throw createHttpError('接单账号待处理，暂无法登录', {
      statusCode: 403,
      errorCode: 'worker_pending_review',
    })
  }

  throw createHttpError('接单账号已停用', {
    statusCode: 403,
    errorCode: 'worker_disabled',
  })
}

export function normalizeWorkerDeviceType(value: unknown): string {
  const type = String(value || '')
    .trim()
    .toLowerCase()
  return type === 'mobile' || type === 'tablet' ? 'mobile' : 'pc'
}

export function normalizeWorkerDeviceId(value: unknown, fallback: string): string {
  const deviceId = String(value || '').trim()
  return (deviceId || fallback).slice(0, 200)
}

export function normalizeWorkerDeviceName(value: unknown, deviceType: string): string {
  const name = String(value || '').trim()
  return (name || (deviceType === 'pc' ? 'PC 浏览器' : '移动设备')).slice(0, 100)
}
