import { NextRequest, NextResponse } from 'next/server'
import { 
  validateApiKey,
  getProjectCustomDomain,
  removeCustomDomain,
} from '@/lib/storage/blob'
import { normalizeDomain } from '@/lib/docs/config'

/**
 * DELETE /api/domains/remove
 * 
 * Remove a custom domain from a project.
 * 
 * Headers:
 *   Authorization: Bearer <api_key>
 * 
 * Body:
 *   { customDomain: "docs.example.com" }  // Optional, removes project's domain if not specified
 * 
 * Response:
 *   {
 *     success: true,
 *     message: "Domain docs.example.com removed successfully"
 *   }
 */
export async function DELETE(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 }
      )
    }
    
    // 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' },
          { status: 404 }
        )
      }
      customDomain = projectDomain.customDomain
    }
    
    // Remove the domain
    const result = await removeCustomDomain(customDomain, projectSlug)
    
    if (!result.success) {
      return NextResponse.json(
        { error: result.error },
        { status: 400 }
      )
    }
    
    // TODO: In production, also remove from Vercel via API
    // await vercelApi.removeDomain(customDomain)
    
    return NextResponse.json({
      success: true,
      message: `Domain ${customDomain} removed successfully`,
      domain: customDomain,
      projectSlug,
    })
    
  } catch (error) {
    console.error('[Domains API] Error removing domain:', error)
    const message = error instanceof Error ? error.message : String(error)
    return NextResponse.json(
      { error: 'Failed to remove domain', details: message },
      { status: 500 }
    )
  }
}

/**
 * POST /api/domains/remove
 * 
 * Alternative method for removing domain (some clients don't support DELETE with body)
 */
export async function POST(request: NextRequest) {
  return DELETE(request)
}
