import 'server-only'
import { randomBytes } from 'crypto'
import pool from '@/lib/db'

// Alphanumeric, confusable chars removed (0, 1, i, l, o)
const CHARS = 'abcdefghjkmnpqrstuvwxyz23456789'

function generateCode(): string {
  const bytes = randomBytes(6)
  return Array.from(bytes, b => CHARS[b % CHARS.length]).join('')
}

export async function createShortLink(token: string): Promise<string> {
  for (let attempt = 0; attempt < 10; attempt++) {
    const code = generateCode()
    try {
      await pool.query(
        `INSERT INTO pitch_short_links (short_code, token) VALUES ($1, $2)`,
        [code, token],
      )
      const baseUrl = process.env.PITCH_BASE_URL || 'https://pitch.breakpilot.ai'
      return `${baseUrl}/p/${code}`
    } catch {
      // Unique constraint collision — retry with a new code
    }
  }
  throw new Error('Failed to generate unique short code after 10 attempts')
}
