import { NextResponse } from 'next/server';
import { validateApiKey, getProjectCustomDomain, getCustomDomainEntry, updateCustomDomainStatus } from '@/lib/storage/blob';
import { normalizeDomain } from '@/lib/docs/config';
import dns from 'dns';
import { promisify } from 'util';
const resolveCname = promisify(dns.resolveCname);
const resolveTxt = promisify(dns.resolveTxt);
/**
 * POST /api/domains/verify
 * 
 * Verify DNS configuration for a custom domain.
 * Checks CNAME and TXT records, then triggers SSL provisioning.
 * 
 * Headers:
 *   Authorization: Bearer <api_key>
 * 
 * Body:
 *   { customDomain: "docs.example.com" }  // Optional, uses project's domain if not specified
 * 
 * Response:
 *   {
 *     success: true,
 *     domain: "docs.example.com",
 *     status: "dns_verified",
 *     checks: {
 *       cname: { found: true, value: "cname.devdoc-dns.com" },
 *       txt: { found: true, verified: true }
 *     }
 *   }
 */ 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().catch(()=>({}));
        let customDomain = body.customDomain ? normalizeDomain(body.customDomain) : null;
        // If no domain specified, get the project's custom domain
        if (!customDomain) {
            const projectDomain = await getProjectCustomDomain(projectSlug);
            if (!projectDomain) {
                return NextResponse.json({
                    error: 'No custom domain configured for this project. Add one first with /api/domains/add'
                }, {
                    status: 404
                });
            }
            customDomain = projectDomain.customDomain;
        }
        // Get domain entry
        const domainEntry = await getCustomDomainEntry(customDomain);
        if (!domainEntry) {
            return NextResponse.json({
                error: `Domain ${customDomain} not found`
            }, {
                status: 404
            });
        }
        // Verify domain belongs to this project
        if (domainEntry.projectSlug !== projectSlug) {
            return NextResponse.json({
                error: `Domain ${customDomain} does not belong to this project`
            }, {
                status: 403
            });
        }
        // Check DNS records
        const checks = {
            cname: {
                found: false,
                value: null,
                expected: 'cname.devdoc-dns.com'
            },
            txt: {
                found: false,
                verified: false,
                expected: domainEntry.verificationToken
            }
        };
        // Check CNAME record
        try {
            const cnameRecords = await resolveCname(customDomain);
            if (cnameRecords && cnameRecords.length > 0) {
                checks.cname.found = true;
                checks.cname.value = cnameRecords[0];
            }
        } catch  {
        // CNAME not found or DNS error
        }
        // Check TXT record for verification
        const txtRecordName = `_devdoc-verify.${customDomain}`;
        try {
            const txtRecords = await resolveTxt(txtRecordName);
            if (txtRecords && txtRecords.length > 0) {
                checks.txt.found = true;
                // TXT records can be arrays, flatten and check
                const allTxtValues = txtRecords.flat();
                checks.txt.verified = allTxtValues.some((val)=>val === domainEntry.verificationToken);
            }
        } catch  {
        // TXT not found or DNS error
        }
        // Determine overall status
        const cnameValid = checks.cname.found && checks.cname.value?.toLowerCase().includes('devdoc');
        const txtValid = checks.txt.found && checks.txt.verified;
        let newStatus = domainEntry.status;
        let message = '';
        if (cnameValid && txtValid) {
            // DNS is verified, update status
            newStatus = 'dns_verified';
            message = 'DNS verified! SSL certificate will be provisioned automatically (1-24 hours).';
            await updateCustomDomainStatus(customDomain, 'dns_verified');
        // In production, this would trigger Vercel API to add domain
        // For now, we simulate SSL provisioning by updating status
        // TODO: Integrate with Vercel Domains API
        } else if (cnameValid && !txtValid) {
            message = 'CNAME record found, but TXT verification record is missing or incorrect.';
        } else if (!cnameValid && txtValid) {
            message = 'TXT verification found, but CNAME record is missing or incorrect.';
        } else {
            message = 'DNS records not found. Please add the required CNAME and TXT records.';
        }
        return NextResponse.json({
            success: cnameValid && txtValid,
            domain: customDomain,
            projectSlug,
            status: newStatus,
            message,
            checks: {
                cname: {
                    found: checks.cname.found,
                    value: checks.cname.value,
                    valid: cnameValid,
                    expected: checks.cname.expected
                },
                txt: {
                    found: checks.txt.found,
                    verified: checks.txt.verified,
                    expected: checks.txt.expected
                }
            }
        });
    } catch (error) {
        console.error('[Domains API] Error verifying domain:', error);
        const message = error instanceof Error ? error.message : String(error);
        return NextResponse.json({
            error: 'Failed to verify domain',
            details: message
        }, {
            status: 500
        });
    }
}
