import { NextRequest, NextResponse } from 'next/server'
import { TOMGeneratorState } from '@/lib/sdk/tom-generator/types'
import { generateDOCXContent, generateDOCXFilename } from '@/lib/sdk/tom-generator/export/docx'
import { generatePDFContent, generatePDFFilename } from '@/lib/sdk/tom-generator/export/pdf'
import { generateZIPFiles, generateZIPFilename } from '@/lib/sdk/tom-generator/export/zip'
import crypto from 'crypto'

/**
 * TOM Generator Export API
 *
 * POST /api/sdk/v1/tom-generator/export - Generate export
 *
 * Request body:
 * {
 *   tenantId: string
 *   format: 'DOCX' | 'PDF' | 'JSON' | 'ZIP'
 *   language: 'de' | 'en'
 *   state: TOMGeneratorState
 *   options?: {
 *     includeEvidence?: boolean
 *     includeGapAnalysis?: boolean
 *     companyLogo?: string (base64)
 *   }
 * }
 */

// In-memory export store for tracking exports
interface StoredExport {
  id: string
  tenantId: string
  format: string
  filename: string
  content: string // Base64 encoded content
  generatedAt: Date
  size: number
}

const exportStore: Map<string, StoredExport> = new Map()

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { tenantId, format, language = 'de', state, options = {} } = body

    if (!tenantId) {
      return NextResponse.json(
        { success: false, error: 'tenantId is required' },
        { status: 400 }
      )
    }

    if (!format) {
      return NextResponse.json(
        { success: false, error: 'format is required (DOCX, PDF, JSON, ZIP)' },
        { status: 400 }
      )
    }

    if (!state) {
      return NextResponse.json(
        { success: false, error: 'state is required' },
        { status: 400 }
      )
    }

    // Parse dates in state
    const parsedState: TOMGeneratorState = {
      ...state,
      createdAt: new Date(state.createdAt),
      updatedAt: new Date(state.updatedAt),
      steps: state.steps?.map((step: { id: string; completed: boolean; data: unknown; validatedAt: string | null }) => ({
        ...step,
        validatedAt: step.validatedAt ? new Date(step.validatedAt) : null,
      })) || [],
      documents: state.documents?.map((doc: { uploadedAt: string; validFrom?: string; validUntil?: string; aiAnalysis?: { analyzedAt: string } }) => ({
        ...doc,
        uploadedAt: new Date(doc.uploadedAt),
        validFrom: doc.validFrom ? new Date(doc.validFrom) : null,
        validUntil: doc.validUntil ? new Date(doc.validUntil) : null,
        aiAnalysis: doc.aiAnalysis ? {
          ...doc.aiAnalysis,
          analyzedAt: new Date(doc.aiAnalysis.analyzedAt),
        } : null,
      })) || [],
      derivedTOMs: state.derivedTOMs?.map((tom: { implementationDate?: string; reviewDate?: string }) => ({
        ...tom,
        implementationDate: tom.implementationDate ? new Date(tom.implementationDate) : null,
        reviewDate: tom.reviewDate ? new Date(tom.reviewDate) : null,
      })) || [],
      gapAnalysis: state.gapAnalysis ? {
        ...state.gapAnalysis,
        generatedAt: new Date(state.gapAnalysis.generatedAt),
      } : null,
      exports: state.exports?.map((exp: { generatedAt: string }) => ({
        ...exp,
        generatedAt: new Date(exp.generatedAt),
      })) || [],
    }

    const exportId = crypto.randomUUID()
    let content: string
    let filename: string
    let mimeType: string

    switch (format.toUpperCase()) {
      case 'DOCX': {
        // Generate DOCX structure (actual binary conversion would require docx library)
        const docxContent = generateDOCXContent(parsedState, { language: language as 'de' | 'en', ...options })
        content = Buffer.from(JSON.stringify(docxContent, null, 2)).toString('base64')
        filename = generateDOCXFilename(parsedState, language as 'de' | 'en')
        mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        break
      }

      case 'PDF': {
        // Generate PDF structure (actual binary conversion would require pdf library)
        const pdfContent = generatePDFContent(parsedState, { language: language as 'de' | 'en', ...options })
        content = Buffer.from(JSON.stringify(pdfContent, null, 2)).toString('base64')
        filename = generatePDFFilename(parsedState, language as 'de' | 'en')
        mimeType = 'application/pdf'
        break
      }

      case 'JSON':
        content = Buffer.from(JSON.stringify(parsedState, null, 2)).toString('base64')
        filename = `tom-export-${tenantId}-${new Date().toISOString().split('T')[0]}.json`
        mimeType = 'application/json'
        break

      case 'ZIP': {
        const files = generateZIPFiles(parsedState, { language: language as 'de' | 'en', ...options })
        // For now, return the files metadata (actual ZIP generation would require a library)
        content = Buffer.from(JSON.stringify(files, null, 2)).toString('base64')
        filename = generateZIPFilename(parsedState, language as 'de' | 'en')
        mimeType = 'application/zip'
        break
      }

      default:
        return NextResponse.json(
          { success: false, error: `Unsupported format: ${format}` },
          { status: 400 }
        )
    }

    // Store the export
    const storedExport: StoredExport = {
      id: exportId,
      tenantId,
      format: format.toUpperCase(),
      filename,
      content,
      generatedAt: new Date(),
      size: Buffer.from(content, 'base64').length,
    }
    exportStore.set(exportId, storedExport)

    return NextResponse.json({
      success: true,
      data: {
        exportId,
        filename,
        format: format.toUpperCase(),
        mimeType,
        size: storedExport.size,
        generatedAt: storedExport.generatedAt.toISOString(),
        downloadUrl: `/api/sdk/v1/tom-generator/export?exportId=${exportId}`,
      },
    })
  } catch (error) {
    console.error('Failed to generate export:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to generate export' },
      { status: 500 }
    )
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const exportId = searchParams.get('exportId')

    if (!exportId) {
      return NextResponse.json(
        { success: false, error: 'exportId is required' },
        { status: 400 }
      )
    }

    const storedExport = exportStore.get(exportId)
    if (!storedExport) {
      return NextResponse.json(
        { success: false, error: `Export not found: ${exportId}` },
        { status: 404 }
      )
    }

    // Return the file as download
    const buffer = Buffer.from(storedExport.content, 'base64')

    let mimeType: string
    switch (storedExport.format) {
      case 'DOCX':
        mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        break
      case 'PDF':
        mimeType = 'application/pdf'
        break
      case 'JSON':
        mimeType = 'application/json'
        break
      case 'ZIP':
        mimeType = 'application/zip'
        break
      default:
        mimeType = 'application/octet-stream'
    }

    return new NextResponse(buffer, {
      headers: {
        'Content-Type': mimeType,
        'Content-Disposition': `attachment; filename="${storedExport.filename}"`,
        'Content-Length': buffer.length.toString(),
      },
    })
  } catch (error) {
    console.error('Failed to download export:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to download export' },
      { status: 500 }
    )
  }
}

export async function OPTIONS() {
  return NextResponse.json(
    { status: 'ok' },
    {
      headers: {
        Allow: 'GET, POST, OPTIONS',
      },
    }
  )
}
