import { NextRequest, NextResponse } from "next/server"
import { query } from "@/lib/db"
import crypto from "crypto"

export async function POST(request: NextRequest) {
  try {
    const { phone, token: clientToken } = await request.json()
    if (!phone) {
      return NextResponse.json({ error: "Phone number required" }, { status: 400 })
    }

    const token = clientToken || crypto.randomBytes(24).toString("hex")
    await query(
      `INSERT INTO invites (token, phone) VALUES ($1, $2)`,
      [token, phone],
    )

    const origin = request.headers.get("origin") || "http://localhost:3000"
    const inviteUrl = `${origin}/join/${token}`

    return NextResponse.json({ token, inviteUrl })
  } catch {
    return NextResponse.json({ error: "Failed to generate invite" }, { status: 500 })
  }
}
