import { type NextRequest, NextResponse } from "next/server"
import crypto from "crypto"

// 存客宝API配置
const CKB_API_KEY = "fyngh-ecy9h-qkdae-epwd5-rz6kd"
const CKB_API_URL = "https://ckbapi.quwanzhi.com/v1/api/scenarios"

// 生成签名
function generateSign(apiKey: string, timestamp: number): string {
  const signStr = `${apiKey}${timestamp}`
  return crypto.createHash("md5").update(signStr).digest("hex")
}

// 不同类型对应的source标签
const sourceMap: Record<string, string> = {
  team: "团队招募",
  investor: "资源对接",
  mentor: "导师顾问",
}

const tagsMap: Record<string, string> = {
  team: "切片团队,团队招募",
  investor: "资源对接,资源群",
  mentor: "导师顾问,咨询服务",
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { type, phone, name, wechatId, remark } = body

    // 验证必填参数
    if (!type || !phone) {
      return NextResponse.json({ success: false, message: "缺少必填参数" }, { status: 400 })
    }

    // 验证类型
    if (!["team", "investor", "mentor"].includes(type)) {
      return NextResponse.json({ success: false, message: "无效的加入类型" }, { status: 400 })
    }

    // 生成时间戳和签名
    const timestamp = Math.floor(Date.now() / 1000)
    const sign = generateSign(CKB_API_KEY, timestamp)

    // 构建请求参数
    const requestBody = {
      apiKey: CKB_API_KEY,
      sign,
      timestamp,
      phone,
      name: name || "",
      wechatId: wechatId || "",
      source: sourceMap[type],
      remark: remark || `来自创业实验APP-${sourceMap[type]}`,
      tags: tagsMap[type],
    }

    // 调用存客宝API
    const response = await fetch(CKB_API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestBody),
    })

    const result = await response.json()

    if (response.ok && result.code === 0) {
      return NextResponse.json({
        success: true,
        message: `成功加入${sourceMap[type]}`,
        data: result.data,
      })
    } else {
      return NextResponse.json({
        success: false,
        message: result.message || "加入失败，请稍后重试",
      })
    }
  } catch (error) {
    console.error("存客宝API调用失败:", error)
    return NextResponse.json({ success: false, message: "服务器错误，请稍后重试" }, { status: 500 })
  }
}
