import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { generateToken } from '@/lib/auth'
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
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, data_masked_at 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.data_masked_at) {
    return NextResponse.json(
      { error: 'Investor data has been anonymized after the 72h window. Cannot generate a new link.' },
      { status: 410 },
    )
  }
  if (investor.status === 'revoked') {
    return NextResponse.json(
      { error: 'Investor is revoked. Re-invite to reactivate.' },
      { status: 400 },
    )
  }

  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 baseUrl = process.env.PITCH_BASE_URL || 'https://pitch.breakpilot.ai'
  const url = `${baseUrl}/auth/verify?token=${token}`
  const shortUrl = await createShortLink(token)

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

  return NextResponse.json({ url, short_url: shortUrl, expires_at: expiresAt.toISOString() })
}
