import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'

interface Ctx { params: Promise<{ code: string }> }

const BASE_URL = process.env.PITCH_BASE_URL || 'https://pitch.breakpilot.com'

export async function GET(request: NextRequest, ctx: Ctx) {
  const { code } = await ctx.params

  const { rows } = await pool.query(
    `SELECT sl.token FROM pitch_short_links sl
     JOIN pitch_magic_links ml ON ml.token = sl.token
     WHERE sl.short_code = $1 AND ml.expires_at > NOW()`,
    [code.toLowerCase()],
  )

  if (rows.length === 0) {
    return NextResponse.redirect(`${BASE_URL}/auth?error=invalid`)
  }

  return NextResponse.redirect(`${BASE_URL}/auth/verify?token=${rows[0].token}`)
}
