import { NextRequest, NextResponse } from 'next/server'
import crypto from 'crypto'
import { invitationRepo } from '@/lib/database/repositories/invitation.repo'
import { verificationRepo } from '@/lib/database/repositories/verification.repo'
import { sendAliyunSMS } from '@/lib/sms/aliyun'

const CODE_EXPIRY_SECONDS = 300 // 5 minutes
const RESEND_COOLDOWN_SECONDS = 60

/**
 * POST /api/invite/[token]/verify-phone
 *
 * Body:
 *   { action: "send-code", phone: "138xxxx" }  → send SMS code
 *   { action: "verify", phone: "138xxxx", code: "123456" } → verify code
 *
 * This is a public endpoint (no auth required) — the invite token is the auth.
 */
export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ token: string }> },
) {
  const { token } = await params

  // Validate invitation exists
  const invite = invitationRepo.findByInviteToken(token)
  if (!invite) {
    return NextResponse.json({ error: 'Invitation not found' }, { status: 404 })
  }

  // Check expired
  const now = Math.floor(Date.now() / 1000)
  if (now > invite.expiresAt && invite.status !== 'completed') {
    if (invite.status !== 'expired') {
      invitationRepo.markExpired(invite.id)
    }
    return NextResponse.json({ error: 'This invitation has expired' }, { status: 410 })
  }

  // Only allow phone verification from 'pending' state
  if (invite.status !== 'pending' && invite.status !== 'phone_verified') {
    return NextResponse.json(
      { error: `Cannot verify phone in status: ${invite.status}` },
      { status: 400 },
    )
  }

  let body: { action?: string; phone?: string; code?: string }
  try {
    body = await req.json()
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
  }

  const { action, phone, code } = body
  if (!action || !phone) {
    return NextResponse.json({ error: 'action and phone are required' }, { status: 400 })
  }

  // ── Send verification code ────────────────────────────────────
  if (action === 'send-code') {
    // Rate limiting: check last sent code
    const lastCode = verificationRepo.findLatestByIdentifier(phone)

    if (lastCode && lastCode.expiresAt) {
      const elapsed = now - (lastCode.expiresAt - CODE_EXPIRY_SECONDS)
      if (elapsed < RESEND_COOLDOWN_SECONDS) {
        return NextResponse.json(
          {
            error: `请 ${RESEND_COOLDOWN_SECONDS - elapsed} 秒后重试`,
            retryAfter: RESEND_COOLDOWN_SECONDS - elapsed,
          },
          { status: 429 },
        )
      }
    }

    // Generate code
    const codeValue = String(Math.floor(100000 + Math.random() * 900000))
    const codeExpiresAt = now + CODE_EXPIRY_SECONDS

    verificationRepo.create({
      id: crypto.randomUUID(),
      identifier: phone,
      value: codeValue,
      expiresAt: codeExpiresAt,
      createdAt: now,
      updatedAt: now,
    })

    // Send SMS
    if (process.env.NODE_ENV === 'development') {
      console.log(`[DEV SMS] ${phone}: ${codeValue}`)
      return NextResponse.json({
        success: true,
        message: '验证码已发送',
        _devCode: codeValue,
      })
    }

    const result = await sendAliyunSMS(phone, codeValue)
    if (!result.success) {
      return NextResponse.json({ error: result.error || '短信发送失败' }, { status: 500 })
    }
    return NextResponse.json({ success: true, message: '验证码已发送' })
  }

  // ── Verify code ──────────────────────────────────────────────
  if (action === 'verify') {
    if (!code) {
      return NextResponse.json({ error: 'code is required' }, { status: 400 })
    }

    const record = verificationRepo.findLatestByIdentifier(phone)

    if (!record) {
      return NextResponse.json({ error: '请先获取验证码' }, { status: 400 })
    }
    if (record.expiresAt && now > record.expiresAt) {
      return NextResponse.json({ error: '验证码已过期，请重新获取' }, { status: 400 })
    }
    if (record.value !== code) {
      return NextResponse.json({ error: '验证码错误' }, { status: 400 })
    }

    invitationRepo.markPhoneVerified(invite.id, phone)
    return NextResponse.json({ success: true, message: '手机验证成功' })
  }

  return NextResponse.json({ error: 'Invalid action' }, { status: 400 })
}
