// ── Invite: Generate ─────────────────────────────────────────────────────────
// POST /api/invite/generate  — Generate an invite link for a phone number
//
// Auth: super_admin only
// Rate-limited to 10 invites per hour. Creates a cryptographically random
// token and returns a full URL for sharing.

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

// ── POST ─────────────────────────────────────────────────────────────────────

export async function POST(request: NextRequest) {
  try {
    const sessionUser = await getSessionUser()
    if (!sessionUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }
    if (sessionUser.role !== "super_admin") {
      return NextResponse.json({ error: "Only SUPER_ADMIN can generate invites." }, { status: 403 })
    }

    const { phone } = await request.json()
    if (!phone) {
      return NextResponse.json({ error: "Phone number required" }, { status: 400 })
    }

    const ipAddress =
      request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
      request.headers.get("x-real-ip") ||
      "127.0.0.1"

    await setSessionContext(sessionUser.id, ipAddress)

    // Rate limit: max 10 invites per rolling hour
    const recentCount = await query(
      `SELECT COUNT(*) AS cnt FROM invites WHERE created_at > NOW() - INTERVAL '1 hour'`,
    )
    if (parseInt(recentCount.rows[0]?.cnt || "0", 10) >= 10) {
      return NextResponse.json({ error: "Rate limit exceeded. Try again later." }, { status: 429 })
    }

    // Generate a 48-character hex token using cryptographically secure random bytes
    const token = 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 (error) {
    console.error("Invite generation error:", error)
    return NextResponse.json({ error: "Failed to generate invite" }, { status: 500 })
  }
}
