/**
 * Demo Data Seeding for AI Compliance SDK
 *
 * IMPORTANT: Demo data is NOT hardcoded in the frontend.
 * This module provides seed data that gets stored via the API,
 * exactly like real customer data would be stored.
 *
 * The seedDemoData() function writes data through the API,
 * and the data is then loaded from the database like any other data.
 *
 * generateDemoState lives in ./demo-state.ts (barrel split).
 */

import { SDKState } from '../types'
import { getSDKApiClient } from '../api-client'

// Seed data imports (these are templates, not runtime data)
import { getDemoUseCases, DEMO_USE_CASES } from './use-cases'
import { getDemoRisks, DEMO_RISKS } from './risks'
import { getDemoControls, DEMO_CONTROLS } from './controls'
import { getDemoDSFA, DEMO_DSFA } from './dsfa'
import { getDemoTOMs, DEMO_TOMS } from './toms'
import { getDemoProcessingActivities, getDemoRetentionPolicies, DEMO_PROCESSING_ACTIVITIES, DEMO_RETENTION_POLICIES } from './vvt'

// Re-export for direct access to seed templates (for testing/development)
export {
  getDemoUseCases,
  getDemoRisks,
  getDemoControls,
  getDemoDSFA,
  getDemoTOMs,
  getDemoProcessingActivities,
  getDemoRetentionPolicies,
  // Raw data exports
  DEMO_USE_CASES,
  DEMO_RISKS,
  DEMO_CONTROLS,
  DEMO_DSFA,
  DEMO_TOMS,
  DEMO_PROCESSING_ACTIVITIES,
  DEMO_RETENTION_POLICIES,
}

// Re-export generateDemoState from its own module
export { generateDemoState } from './demo-state'
import { generateDemoState } from './demo-state'

/**
 * Seed demo data into the database via API
 * This ensures demo data is stored exactly like real customer data
 */
export async function seedDemoData(
  tenantId: string = 'demo-tenant',
  userId: string = 'demo-user',
  apiBaseUrl?: string
): Promise<{ success: boolean; message: string }> {
  try {
    const apiClient = getSDKApiClient(tenantId)

    // Generate the demo state
    const demoState = generateDemoState(tenantId, userId) as SDKState

    // Save via the same API that real data uses
    await apiClient.saveState(demoState)

    return {
      success: true,
      message: `Demo data successfully seeded for tenant ${tenantId}`,
    }
  } catch (error) {
    console.error('Failed to seed demo data:', error)
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Unknown error during seeding',
    }
  }
}

/**
 * Check if demo data exists for a tenant
 */
export async function hasDemoData(tenantId: string = 'demo-tenant'): Promise<boolean> {
  try {
    const apiClient = getSDKApiClient(tenantId)
    const response = await apiClient.getState()

    // Check if we have any use cases (indicating data exists)
    return response !== null && response.state && Array.isArray(response.state.useCases) && response.state.useCases.length > 0
  } catch {
    return false
  }
}

/**
 * Clear demo data for a tenant
 */
export async function clearDemoData(tenantId: string = 'demo-tenant'): Promise<boolean> {
  try {
    const apiClient = getSDKApiClient(tenantId)
    await apiClient.deleteState()
    return true
  } catch {
    return false
  }
}

/**
 * Seed demo data via direct API call (for use outside of React context)
 * This is useful for server-side seeding or CLI tools
 */
export async function seedDemoDataDirect(
  baseUrl: string,
  tenantId: string = 'demo-tenant',
  userId: string = 'demo-user'
): Promise<{ success: boolean; message: string }> {
  try {
    const demoState = generateDemoState(tenantId, userId)

    const response = await fetch(`${baseUrl}/api/sdk/v1/state`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        tenantId,
        userId,
        state: demoState,
      }),
    })

    if (!response.ok) {
      const error = await response.json().catch(() => ({ message: 'Unknown error' }))
      throw new Error(error.message || `HTTP ${response.status}`)
    }

    return {
      success: true,
      message: `Demo data successfully seeded for tenant ${tenantId}`,
    }
  } catch (error) {
    console.error('Failed to seed demo data:', error)
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Unknown error during seeding',
    }
  }
}
