import { NextRequest, NextResponse } from 'next/server'
import { isSubdomainRegistered } from '@/lib/storage/blob'

// Reserved/blacklisted subdomains
const BLACKLISTED_SUBDOMAINS = new Set([
  // Generic reserved
  'www',
  'api',
  'app',
  'admin',
  'dashboard',
  'console',
  'panel',
  'manage',
  'login',
  'signin',
  'signup',
  'register',
  'auth',
  'oauth',
  'sso',
  // Brand/product
  'devdoc',
  'brainfish',
  'docs',
  'documentation',
  'help',
  'support',
  'status',
  'blog',
  'news',
  // Infrastructure
  'mail',
  'email',
  'smtp',
  'ftp',
  'cdn',
  'static',
  'assets',
  'images',
  'files',
  'media',
  'download',
  'downloads',
  // Common
  'test',
  'testing',
  'dev',
  'development',
  'staging',
  'prod',
  'production',
  'demo',
  'example',
  'sandbox',
  'preview',
  // Security
  'secure',
  'ssl',
  'security',
  'abuse',
  'spam',
  'postmaster',
  'hostmaster',
  'webmaster',
  // Misc
  'null',
  'undefined',
  'true',
  'false',
  'root',
  'system',
  'localhost',
])

interface CheckRequest {
  subdomain: string
}

/**
 * POST /api/subdomains/check
 * Check if a subdomain is available
 * 
 * Body:
 *   subdomain: string - The subdomain to check
 * 
 * Returns:
 *   available: boolean
 *   error?: string - If not available, why
 *   suggestion?: string - Alternative suggestion
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json() as CheckRequest
    const { subdomain } = body
    
    if (!subdomain) {
      return NextResponse.json(
        { available: false, error: 'Subdomain is required' },
        { status: 400 }
      )
    }
    
    // Normalize subdomain
    const normalized = subdomain.toLowerCase().trim()
    
    // Format validation
    if (normalized.length < 3) {
      return NextResponse.json({
        available: false,
        error: 'Subdomain must be at least 3 characters',
      })
    }
    
    if (normalized.length > 63) {
      return NextResponse.json({
        available: false,
        error: 'Subdomain must be 63 characters or less',
      })
    }
    
    if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(normalized)) {
      return NextResponse.json({
        available: false,
        error: 'Subdomain must start and end with alphanumeric characters, and can only contain lowercase letters, numbers, and hyphens',
      })
    }
    
    if (/--/.test(normalized)) {
      return NextResponse.json({
        available: false,
        error: 'Subdomain cannot contain consecutive hyphens',
      })
    }
    
    // Check blacklist
    if (BLACKLISTED_SUBDOMAINS.has(normalized)) {
      // Generate suggestion
      const suggestion = `${normalized}-docs`
      return NextResponse.json({
        available: false,
        error: `"${normalized}" is a reserved subdomain`,
        suggestion,
      })
    }
    
    // Check if subdomain is already registered (O(1) lookup from registry)
    const exists = await isSubdomainRegistered(normalized)
    
    if (exists) {
      // Generate suggestion with random suffix
      const suffix = Math.random().toString(36).substring(2, 6)
      const suggestion = `${normalized}-${suffix}`
      return NextResponse.json({
        available: false,
        error: `"${normalized}" is already taken`,
        suggestion,
      })
    }
    
    return NextResponse.json({
      available: true,
    })
    
  } catch (error) {
    console.error('[Subdomains API] Check Error:', error)
    return NextResponse.json(
      { available: false, error: 'Internal server error' },
      { status: 500 }
    )
  }
}
