import { NextResponse } from 'next/server';
import { isSubdomainRegistered, registerSubdomain, generateApiKey, storeProjectApiKey } from '@/lib/storage/blob';
// Reserved/blacklisted subdomains (same as in subdomains/check)
const BLACKLISTED_SUBDOMAINS = new Set([
    'www',
    'api',
    'app',
    'admin',
    'dashboard',
    'console',
    'panel',
    'manage',
    'login',
    'signin',
    'signup',
    'register',
    'auth',
    'oauth',
    'sso',
    'devdoc',
    'brainfish',
    'docs',
    'documentation',
    'help',
    'support',
    'status',
    'blog',
    'news',
    'mail',
    'email',
    'smtp',
    'ftp',
    'cdn',
    'static',
    'assets',
    'images',
    'files',
    'media',
    'download',
    'downloads',
    'test',
    'testing',
    'dev',
    'development',
    'staging',
    'prod',
    'production',
    'demo',
    'example',
    'sandbox',
    'preview',
    'secure',
    'ssl',
    'security',
    'abuse',
    'spam',
    'postmaster',
    'hostmaster',
    'webmaster',
    'null',
    'undefined',
    'true',
    'false',
    'root',
    'system',
    'localhost'
]);
/**
 * POST /api/projects/register
 * Register a new project and generate an API key
 * 
 * Body:
 *   name: string - Project display name
 *   slug: string - Project slug (URL-safe identifier)
 *   subdomain: string - Desired subdomain for <subdomain>.devdoc.sh
 * 
 * Returns:
 *   success: boolean
 *   projectId: string
 *   slug: string
 *   subdomain: string
 *   apiKey: string
 *   url: string
 */ export async function POST(request) {
    try {
        const body = await request.json();
        const { name, slug, subdomain } = body;
        // Validate required fields
        if (!name || !slug || !subdomain) {
            return NextResponse.json({
                error: 'name, slug, and subdomain are required'
            }, {
                status: 400
            });
        }
        // Normalize subdomain
        const normalizedSubdomain = subdomain.toLowerCase().trim();
        // Validate subdomain format
        if (normalizedSubdomain.length < 3) {
            return NextResponse.json({
                error: 'Subdomain must be at least 3 characters'
            }, {
                status: 400
            });
        }
        if (normalizedSubdomain.length > 63) {
            return NextResponse.json({
                error: 'Subdomain must be 63 characters or less'
            }, {
                status: 400
            });
        }
        if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(normalizedSubdomain)) {
            return NextResponse.json({
                error: 'Subdomain must start and end with alphanumeric characters'
            }, {
                status: 400
            });
        }
        // Check blacklist
        if (BLACKLISTED_SUBDOMAINS.has(normalizedSubdomain)) {
            return NextResponse.json({
                error: `"${normalizedSubdomain}" is a reserved subdomain`
            }, {
                status: 400
            });
        }
        // Use subdomain as the project identifier (slug)
        // This ensures subdomain uniqueness = project uniqueness
        const projectSlug = normalizedSubdomain;
        // Check if subdomain already registered (O(1) lookup from registry)
        const exists = await isSubdomainRegistered(projectSlug);
        if (exists) {
            return NextResponse.json({
                error: `Project with subdomain "${normalizedSubdomain}" already exists`
            }, {
                status: 409
            });
        }
        // Generate API key and project ID
        const apiKey = generateApiKey();
        const projectId = `proj_${projectSlug}_${Math.random().toString(36).substring(2, 8)}`;
        // Register in domain registry (O(1) lookup for future checks)
        await registerSubdomain(projectSlug, projectId, name, apiKey);
        // Also store API key in project folder (for backwards compatibility)
        await storeProjectApiKey(projectSlug, apiKey);
        const response = {
            success: true,
            projectId,
            slug: projectSlug,
            subdomain: normalizedSubdomain,
            apiKey,
            url: `https://${normalizedSubdomain}.devdoc.sh`
        };
        console.log(`[Projects API] Registered new project: ${projectSlug}`);
        return NextResponse.json(response, {
            status: 201
        });
    } catch (error) {
        console.error('[Projects API] Register Error:', error);
        const message = error instanceof Error ? error.message : String(error);
        // Provide clearer error messages for common issues
        let userMessage = 'Failed to register project';
        if (message.includes('blob already exists')) {
            userMessage = 'Project storage conflict. Please try again or use a different subdomain.';
        } else if (message.includes('network') || message.includes('fetch')) {
            userMessage = 'Network error connecting to storage service';
        }
        return NextResponse.json({
            error: userMessage,
            details: message
        }, {
            status: 500
        });
    }
}
