import { NextRequest, NextResponse } from 'next/server'
import { 
  validateApiKey,
  getProjectCustomDomain,
  getCustomDomainEntry,
} from '@/lib/storage/blob'
import { normalizeDomain, getDnsInstructions } from '@/lib/docs/config'
import { getProjectUrl } from '@/lib/multi-tenant/context'

/**
 * GET /api/domains/status
 * 
 * Get the status of a custom domain.
 * 
 * Headers:
 *   Authorization: Bearer <api_key>
 * 
 * Query:
 *   ?domain=docs.example.com  // Optional, uses project's domain if not specified
 * 
 * Response:
 *   {
 *     domain: "docs.example.com",
 *     status: "active",
 *     projectSlug: "my-project",
 *     projectUrl: "https://my-project.devdoc.sh",
 *     customUrl: "https://docs.example.com",
 *     createdAt: "2026-01-24T...",
 *     verifiedAt: "2026-01-24T..."
 *   }
 */
export async function GET(request: NextRequest) {
  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 }
      )
    }
    
    // Get domain from query or use project's domain
    const { searchParams } = new URL(request.url)
    let customDomain = searchParams.get('domain')
    
    if (customDomain) {
      customDomain = normalizeDomain(customDomain)
    }
    
    let domainEntry
    
    if (customDomain) {
      // Get specific domain
      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 }
        )
      }
    } else {
      // Get project's custom domain
      domainEntry = await getProjectCustomDomain(projectSlug)
      
      if (!domainEntry) {
        return NextResponse.json({
          hasCustomDomain: false,
          projectSlug,
          projectUrl: getProjectUrl(projectSlug),
          message: 'No custom domain configured. Use /api/domains/add to add one.',
        })
      }
    }
    
    // Build response based on status
    const projectUrl = getProjectUrl(projectSlug)
    const response: Record<string, unknown> = {
      hasCustomDomain: true,
      domain: domainEntry.customDomain,
      status: domainEntry.status,
      projectSlug,
      projectUrl,
      createdAt: domainEntry.createdAt,
    }
    
    // Add status-specific information
    switch (domainEntry.status) {
      case 'pending': {
        const dnsInstructions = getDnsInstructions(domainEntry.customDomain)
        dnsInstructions.txt.value = domainEntry.verificationToken || ''
        
        response.message = 'Waiting for DNS configuration'
        response.dnsRecords = {
          cname: dnsInstructions.cname,
          txt: dnsInstructions.txt,
        }
        response.nextStep = 'Add the DNS records above, then run "devdoc domain verify"'
        break
      }
      
      case 'dns_verified':
        response.message = 'DNS verified, SSL certificate provisioning in progress'
        response.verifiedAt = domainEntry.verifiedAt
        response.nextStep = 'SSL certificate should be ready within 1-24 hours'
        break
        
      case 'ssl_provisioning':
        response.message = 'SSL certificate being provisioned'
        response.verifiedAt = domainEntry.verifiedAt
        response.nextStep = 'Almost ready! Check back in a few minutes'
        break
        
      case 'active':
        response.message = 'Domain is active and working'
        response.customUrl = `https://${domainEntry.customDomain}`
        response.verifiedAt = domainEntry.verifiedAt
        break
        
      case 'error':
        response.message = 'Domain configuration error'
        response.error = domainEntry.errorMessage
        response.nextStep = 'Check DNS configuration and try verifying again'
        break
    }
    
    response.lastCheckedAt = domainEntry.lastCheckedAt
    
    return NextResponse.json(response)
    
  } catch (error) {
    console.error('[Domains API] Error getting status:', error)
    const message = error instanceof Error ? error.message : String(error)
    return NextResponse.json(
      { error: 'Failed to get domain status', details: message },
      { status: 500 }
    )
  }
}
