import { NextRequest, NextResponse } from 'next/server'
import { EvidenceDocument, DocumentType } from '@/lib/sdk/tom-generator/types'
import { evidenceStore } from '@/lib/sdk/tom-generator/evidence-store'
import crypto from 'crypto'

/**
 * TOM Generator Evidence Upload API
 *
 * POST /api/sdk/v1/tom-generator/evidence/upload - Upload evidence document
 *
 * Request: multipart/form-data
 * - file: File
 * - tenantId: string
 * - documentType: DocumentType
 * - validFrom?: string (ISO date)
 * - validUntil?: string (ISO date)
 * - linkedControlIds?: string (comma-separated)
 */

// Document type detection based on filename patterns
function detectDocumentType(filename: string, mimeType: string): DocumentType {
  const lower = filename.toLowerCase()

  if (lower.includes('avv') || lower.includes('auftragsverarbeitung')) {
    return 'AVV'
  }
  if (lower.includes('dpa') || lower.includes('data processing')) {
    return 'DPA'
  }
  if (lower.includes('sla') || lower.includes('service level')) {
    return 'SLA'
  }
  if (lower.includes('nda') || lower.includes('vertraulichkeit') || lower.includes('geheimhaltung')) {
    return 'NDA'
  }
  if (lower.includes('policy') || lower.includes('richtlinie')) {
    return 'POLICY'
  }
  if (lower.includes('cert') || lower.includes('zertifikat') || lower.includes('iso')) {
    return 'CERTIFICATE'
  }
  if (lower.includes('audit') || lower.includes('prüf') || lower.includes('bericht')) {
    return 'AUDIT_REPORT'
  }

  return 'OTHER'
}

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const file = formData.get('file') as File | null
    const tenantId = formData.get('tenantId') as string | null
    const documentType = formData.get('documentType') as DocumentType | null
    const validFrom = formData.get('validFrom') as string | null
    const validUntil = formData.get('validUntil') as string | null
    const linkedControlIdsStr = formData.get('linkedControlIds') as string | null
    const uploadedBy = formData.get('uploadedBy') as string | null

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

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

    // Read file data
    const arrayBuffer = await file.arrayBuffer()
    const buffer = Buffer.from(arrayBuffer)

    // Generate hash for deduplication
    const hash = crypto.createHash('sha256').update(buffer).digest('hex')

    // Generate unique filename
    const id = crypto.randomUUID()
    const ext = file.name.split('.').pop() || 'bin'
    const filename = `${id}.${ext}`

    // Detect document type if not provided
    const detectedType = detectDocumentType(file.name, file.type)
    const finalDocumentType = documentType || detectedType

    // Parse linked control IDs
    const linkedControlIds = linkedControlIdsStr
      ? linkedControlIdsStr.split(',').map((s) => s.trim()).filter(Boolean)
      : []

    // Create evidence document
    const document: EvidenceDocument = {
      id,
      filename,
      originalName: file.name,
      mimeType: file.type,
      size: file.size,
      uploadedAt: new Date(),
      uploadedBy: uploadedBy || 'unknown',
      documentType: finalDocumentType,
      detectedType,
      hash,
      validFrom: validFrom ? new Date(validFrom) : null,
      validUntil: validUntil ? new Date(validUntil) : null,
      linkedControlIds,
      aiAnalysis: null,
      status: 'PENDING',
    }

    // Store the document metadata
    // Note: In production, the actual file would be stored in MinIO/S3
    await evidenceStore.add(tenantId, document)

    return NextResponse.json({
      success: true,
      data: {
        id: document.id,
        filename: document.filename,
        originalName: document.originalName,
        mimeType: document.mimeType,
        size: document.size,
        documentType: document.documentType,
        detectedType: document.detectedType,
        status: document.status,
        uploadedAt: document.uploadedAt.toISOString(),
      },
      meta: {
        hash,
        needsAnalysis: true,
        analyzeUrl: `/api/sdk/v1/tom-generator/evidence/${id}/analyze`,
      },
    })
  } catch (error) {
    console.error('Failed to upload evidence:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to upload evidence' },
      { status: 500 }
    )
  }
}

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