/**
 * Demo Data Clear API Endpoint
 *
 * Clears demo data from the storage (same mechanism as real customer data).
 */

import { NextRequest, NextResponse } from 'next/server'

// Shared store reference (same as seed endpoint)
declare global {
  // eslint-disable-next-line no-var
  var demoStateStore: Map<string, { state: unknown; version: number; updatedAt: Date }> | undefined
}

if (!global.demoStateStore) {
  global.demoStateStore = new Map()
}

const stateStore = global.demoStateStore

export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json()
    const { tenantId = 'demo-tenant' } = body

    const existed = stateStore.has(tenantId)
    stateStore.delete(tenantId)

    return NextResponse.json({
      success: true,
      message: existed
        ? `Demo data cleared for tenant ${tenantId}`
        : `No data found for tenant ${tenantId}`,
      tenantId,
      existed,
    })
  } catch (error) {
    console.error('Failed to clear demo data:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  // Also support POST for clearing (for clients that don't support DELETE)
  return DELETE(request)
}
