import { NextResponse } from 'next/server';
import { validateApiKey, addCustomDomain, isCustomDomainRegistered } from '@/lib/storage/blob';
import { isValidDomain, normalizeDomain, getDnsInstructions } from '@/lib/docs/config';
/**
 * POST /api/domains/add
 * 
 * Add a custom domain to a project.
 * Each project can have ONE custom domain (free).
 * 
 * Headers:
 *   Authorization: Bearer <api_key>
 * 
 * Body:
 *   { customDomain: "docs.example.com" }
 * 
 * Response:
 *   {
 *     success: true,
 *     domain: "docs.example.com",
 *     status: "pending",
 *     verification: {
 *       cname: { name: "docs", value: "cname.devdoc-dns.com" },
 *       txt: { name: "_devdoc-verify.docs.example.com", value: "devdoc-verify=xxx" }
 *     }
 *   }
 */ export async function POST(request) {
    try {
        // Validate API key
        const authHeader = request.headers.get('Authorization');
        const apiKey = authHeader?.replace('Bearer ', '');
        if (!apiKey) {
            return NextResponse.json({
                error: 'API key required. Provide via Authorization header.'
            }, {
                status: 401
            });
        }
        const projectSlug = await validateApiKey(apiKey);
        if (!projectSlug) {
            return NextResponse.json({
                error: 'Invalid API key'
            }, {
                status: 403
            });
        }
        // Parse request body
        const body = await request.json();
        const { customDomain: rawDomain } = body;
        if (!rawDomain || typeof rawDomain !== 'string') {
            return NextResponse.json({
                error: 'Missing customDomain in request body'
            }, {
                status: 400
            });
        }
        // Normalize and validate domain
        const customDomain = normalizeDomain(rawDomain);
        const validation = isValidDomain(customDomain);
        if (!validation.valid) {
            return NextResponse.json({
                error: validation.error
            }, {
                status: 400
            });
        }
        // Check if domain is already registered
        const isRegistered = await isCustomDomainRegistered(customDomain);
        if (isRegistered) {
            return NextResponse.json({
                error: `Domain ${customDomain} is already registered to another project.`
            }, {
                status: 409
            });
        }
        // Add the custom domain
        const result = await addCustomDomain(projectSlug, customDomain);
        if (!result.success) {
            return NextResponse.json({
                error: result.error
            }, {
                status: 400
            });
        }
        // Get DNS instructions
        const dnsInstructions = getDnsInstructions(customDomain);
        // Add verification token to TXT record
        dnsInstructions.txt.value = result.entry.verificationToken || '';
        return NextResponse.json({
            success: true,
            domain: customDomain,
            projectSlug,
            status: result.entry.status,
            verification: {
                cname: dnsInstructions.cname,
                txt: dnsInstructions.txt
            },
            instructions: [
                'Add the following DNS records to your domain:',
                '',
                `1. CNAME Record:`,
                `   Name: ${dnsInstructions.cname.name}`,
                `   Value: ${dnsInstructions.cname.value}`,
                '',
                `2. TXT Record (for verification):`,
                `   Name: ${dnsInstructions.txt.name}`,
                `   Value: ${dnsInstructions.txt.value}`,
                '',
                'After adding DNS records, run "devdoc domain verify" to verify.'
            ]
        });
    } catch (error) {
        console.error('[Domains API] Error adding domain:', error);
        const message = error instanceof Error ? error.message : String(error);
        return NextResponse.json({
            error: 'Failed to add domain',
            details: message
        }, {
            status: 500
        });
    }
}
