'use server'
import {ApiResponse} from '@/lib/api'
import {callByDevice} from '@/actions/base'
import {getCap} from '@/lib/cap'

export async function sendSMS(props: {
  phone: string
  captcha: string
}): Promise<ApiResponse> {
  try {
    // 人机验证
    if (!props.captcha?.length) {
      return {
        success: false,
        status: 400,
        message: '请输入验证码',
      }
    }

    const cap = await getCap()
    const valid = await cap.validateToken(props.captcha)
    if (!valid) {
      return {
        success: false,
        status: 400,
        message: '验证码错误或已过期',
      }
    }

    // 请求发送短信
    return await callByDevice('/api/auth/verify/sms', {
      phone: props.phone,
      purpose: 0,
    })
  }
  catch (error) {
    console.error('验证码验证失败:', error)
    throw new Error('验证码验证失败', {cause: error})
  }
}
