import { NextRequest, NextResponse } from 'next/server'
import { v4 as uuidv4 } from 'uuid'
import { ProcessingActivity, generateVVTId } from '@/lib/sdk/vendor-compliance'

// In-memory storage for demo purposes
// In production, this would be replaced with database calls
const processingActivities: Map<string, ProcessingActivity> = new Map()

export async function GET(request: NextRequest) {
  try {
    const activities = Array.from(processingActivities.values())

    return NextResponse.json({
      success: true,
      data: activities,
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Error fetching processing activities:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch processing activities' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    // Generate IDs
    const id = uuidv4()
    const existingIds = Array.from(processingActivities.values()).map((a) => a.vvtId)
    const vvtId = body.vvtId || generateVVTId(existingIds)

    const activity: ProcessingActivity = {
      id,
      tenantId: 'default', // Would come from auth context
      vvtId,
      name: body.name,
      responsible: body.responsible,
      dpoContact: body.dpoContact,
      purposes: body.purposes || [],
      dataSubjectCategories: body.dataSubjectCategories || [],
      personalDataCategories: body.personalDataCategories || [],
      recipientCategories: body.recipientCategories || [],
      thirdCountryTransfers: body.thirdCountryTransfers || [],
      retentionPeriod: body.retentionPeriod || { description: { de: '', en: '' } },
      technicalMeasures: body.technicalMeasures || [],
      legalBasis: body.legalBasis || [],
      dataSources: body.dataSources || [],
      systems: body.systems || [],
      dataFlows: body.dataFlows || [],
      protectionLevel: body.protectionLevel || 'MEDIUM',
      dpiaRequired: body.dpiaRequired || false,
      dpiaJustification: body.dpiaJustification,
      subProcessors: body.subProcessors || [],
      legalRetentionBasis: body.legalRetentionBasis,
      status: body.status || 'DRAFT',
      owner: body.owner || '',
      lastReviewDate: body.lastReviewDate,
      nextReviewDate: body.nextReviewDate,
      createdAt: new Date(),
      updatedAt: new Date(),
    }

    processingActivities.set(id, activity)

    return NextResponse.json(
      {
        success: true,
        data: activity,
        timestamp: new Date().toISOString(),
      },
      { status: 201 }
    )
  } catch (error) {
    console.error('Error creating processing activity:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to create processing activity' },
      { status: 500 }
    )
  }
}
