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

// In-memory storage for demo purposes
const vendors: Map<string, Vendor> = new Map()

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

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

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

    const vendor: Vendor = {
      id,
      tenantId: 'default',
      name: body.name,
      legalForm: body.legalForm,
      country: body.country,
      address: body.address,
      website: body.website,
      role: body.role,
      serviceDescription: body.serviceDescription,
      serviceCategory: body.serviceCategory,
      dataAccessLevel: body.dataAccessLevel || 'NONE',
      processingLocations: body.processingLocations || [],
      transferMechanisms: body.transferMechanisms || [],
      certifications: body.certifications || [],
      primaryContact: body.primaryContact,
      dpoContact: body.dpoContact,
      securityContact: body.securityContact,
      contractTypes: body.contractTypes || [],
      contracts: body.contracts || [],
      inherentRiskScore: body.inherentRiskScore || 50,
      residualRiskScore: body.residualRiskScore || 50,
      manualRiskAdjustment: body.manualRiskAdjustment,
      riskJustification: body.riskJustification,
      reviewFrequency: body.reviewFrequency || 'ANNUAL',
      lastReviewDate: body.lastReviewDate,
      nextReviewDate: body.nextReviewDate,
      status: body.status || 'ACTIVE',
      processingActivityIds: body.processingActivityIds || [],
      notes: body.notes,
      createdAt: new Date(),
      updatedAt: new Date(),
    }

    vendors.set(id, vendor)

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