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

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

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

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

export async function POST(request: NextRequest) {
  try {
    // Handle multipart form data for file upload
    const formData = await request.formData()
    const file = formData.get('file') as File | null
    const vendorId = formData.get('vendorId') as string
    const metadataStr = formData.get('metadata') as string

    if (!file || !vendorId) {
      return NextResponse.json(
        { success: false, error: 'File and vendorId are required' },
        { status: 400 }
      )
    }

    const metadata = metadataStr ? JSON.parse(metadataStr) : {}
    const id = uuidv4()

    // In production, upload file to storage (MinIO, S3, etc.)
    const storagePath = `contracts/${id}/${file.name}`

    const contract: ContractDocument = {
      id,
      tenantId: 'default',
      vendorId,
      fileName: `${id}-${file.name}`,
      originalName: file.name,
      mimeType: file.type,
      fileSize: file.size,
      storagePath,
      documentType: metadata.documentType || 'OTHER',
      version: metadata.version || '1.0',
      previousVersionId: metadata.previousVersionId,
      parties: metadata.parties,
      effectiveDate: metadata.effectiveDate ? new Date(metadata.effectiveDate) : undefined,
      expirationDate: metadata.expirationDate ? new Date(metadata.expirationDate) : undefined,
      autoRenewal: metadata.autoRenewal,
      renewalNoticePeriod: metadata.renewalNoticePeriod,
      terminationNoticePeriod: metadata.terminationNoticePeriod,
      reviewStatus: 'PENDING',
      status: 'DRAFT',
      createdAt: new Date(),
      updatedAt: new Date(),
    }

    contracts.set(id, contract)

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