import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { generateToken } from '@/lib/auth'
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
import { sendMagicLinkEmail } from '@/lib/email'
import { checkRateLimit, RATE_LIMITS } from '@/lib/rate-limit'
import { createShortLink } from '@/lib/short-links'

interface RouteContext {
  params: Promise<{ id: string }>
}

export async function POST(request: NextRequest, ctx: RouteContext) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response
  const adminId = guard.kind === 'admin' ? guard.admin.id : null

  const { id } = await ctx.params

  const { rows } = await pool.query(
    `SELECT id, email, name, status FROM pitch_investors WHERE id = $1`,
    [id],
  )
  if (rows.length === 0) {
    return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
  }

  const investor = rows[0]
  if (investor.status === 'revoked') {
    return NextResponse.json({ error: 'Investor is revoked. Reactivate first by re-inviting.' }, { status: 400 })
  }

  // Rate limit by email
  const rl = checkRateLimit(`magic-link:${investor.email}`, RATE_LIMITS.magicLink)
  if (!rl.allowed) {
    return NextResponse.json({ error: 'Too many resends for this email. Try again later.' }, { status: 429 })
  }

  const token = generateToken()
  const ttlHours = parseInt(process.env.MAGIC_LINK_TTL_HOURS || '72')
  const expiresAt = new Date(Date.now() + ttlHours * 60 * 60 * 1000)

  await pool.query(
    `INSERT INTO pitch_magic_links (investor_id, token, expires_at) VALUES ($1, $2, $3)`,
    [investor.id, token, expiresAt],
  )

  const shortUrl = await createShortLink(token)
  await sendMagicLinkEmail(investor.email, investor.name, shortUrl)

  await logAdminAudit(
    adminId,
    'magic_link_resent',
    { email: investor.email, expires_at: expiresAt.toISOString() },
    request,
    investor.id,
  )

  return NextResponse.json({ success: true, expires_at: expiresAt.toISOString() })
}
