/**
 * API Types
 *
 * Type definitions for API communication
 */

import type { SDKState } from './state'
import type { CheckpointStatus, ValidationError } from './base'

// =============================================================================
// API RESPONSE TYPES
// =============================================================================

export interface APIResponse<T = unknown> {
  success: boolean
  data?: T
  error?: string
  message?: string
  version?: number
  timestamp?: string
}

export interface PaginatedResponse<T> {
  data: T[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export interface APIError {
  code: string
  message: string
  details?: Record<string, unknown>
  status: number
  retryable: boolean
}

// =============================================================================
// STATE MANAGEMENT
// =============================================================================

export interface StateResponse {
  tenantId: string
  state: SDKState
  version: number
  lastModified: string
}

export interface SaveStateRequest {
  tenantId: string
  state: SDKState
  version?: number // For optimistic locking
}

// =============================================================================
// CHECKPOINT VALIDATION
// =============================================================================

export interface CheckpointValidationRequest {
  tenantId: string
  checkpointId: string
  data?: unknown
}

export interface CheckpointValidationResult {
  checkpointId: string
  passed: boolean
  errors: ValidationError[]
  warnings: ValidationError[]
  validatedAt: string
  validatedBy: string
}

// =============================================================================
// AUTHENTICATION
// =============================================================================

export interface AuthTokenRequest {
  grantType: 'client_credentials' | 'authorization_code' | 'refresh_token'
  clientId: string
  clientSecret?: string
  code?: string
  refreshToken?: string
  redirectUri?: string
}

export interface AuthTokenResponse {
  accessToken: string
  tokenType: 'Bearer'
  expiresIn: number
  refreshToken?: string
  scope?: string
}

export interface APIKeyInfo {
  id: string
  name: string
  prefix: string
  scopes: string[]
  createdAt: Date
  lastUsedAt?: Date
  expiresAt?: Date
}

// =============================================================================
// SYNC
// =============================================================================

export type SyncStatus = 'idle' | 'syncing' | 'error' | 'offline' | 'conflict'

export interface SyncState {
  status: SyncStatus
  lastSyncedAt: Date | null
  localVersion: number
  serverVersion: number
  pendingChanges: number
  error: string | null
}

export interface ConflictResolution {
  strategy: 'local' | 'server' | 'merge'
  mergedState?: SDKState
}

export interface SyncOptions {
  debounceMs?: number
  maxRetries?: number
  conflictHandler?: (local: SDKState, server: SDKState) => Promise<ConflictResolution>
}

// =============================================================================
// FLOW NAVIGATION
// =============================================================================

export interface FlowStateResponse {
  currentStep: string
  currentPhase: 1 | 2
  completedSteps: string[]
  suggestions: Array<{ stepId: string; reason: string }>
}

export interface FlowNavigationRequest {
  tenantId: string
  direction: 'next' | 'previous'
}

export interface FlowNavigationResponse {
  stepId: string
  phase: 1 | 2
}

// =============================================================================
// EXPORT
// =============================================================================

export type ExportFormat = 'json' | 'pdf' | 'docx' | 'zip' | 'csv'

export interface ExportRequest {
  tenantId: string
  format: ExportFormat
  sections?: string[]
  includeEvidence?: boolean
  language?: 'de' | 'en'
}

export interface ExportResponse {
  id: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  downloadUrl?: string
  expiresAt?: Date
  error?: string
}

// =============================================================================
// RAG API
// =============================================================================

export interface RAGSearchRequest {
  query: string
  filters?: {
    documentCodes?: string[]
    jurisdictions?: string[]
    languages?: string[]
    articles?: string[]
  }
  limit?: number
  offset?: number
}

export interface RAGSearchResponse {
  results: Array<{
    id: string
    documentCode: string
    documentName: string
    content: string
    article?: string
    score: number
    highlights: string[]
  }>
  total: number
  processingTimeMs: number
}

export interface RAGAskRequest {
  question: string
  context?: string
  documents?: string[]
  maxSources?: number
  language?: 'de' | 'en'
}

export interface RAGAskResponse {
  answer: string
  sources: Array<{
    documentCode: string
    documentName: string
    article?: string
    content: string
    relevanceScore: number
  }>
  confidence: number
  processingTimeMs: number
}

// =============================================================================
// DOCUMENT GENERATION
// =============================================================================

export interface GenerateDocumentRequest {
  tenantId: string
  documentType: 'dsfa' | 'tom' | 'vvt' | 'gutachten' | 'privacy_policy' | 'cookie_banner'
  options?: Record<string, unknown>
}

export interface GenerateDocumentResponse {
  id: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  content?: string
  documentUrl?: string
  error?: string
}

// =============================================================================
// SECURITY SCAN
// =============================================================================

export interface SecurityScanRequest {
  tenantId: string
  tools?: string[]
  targetPath?: string
  excludePaths?: string[]
  severityThreshold?: string
  generateSBOM?: boolean
}

export interface SecurityScanResponse {
  id: string
  status: 'queued' | 'running' | 'completed' | 'failed'
  totalIssues?: number
  critical?: number
  high?: number
  medium?: number
  low?: number
  sbomId?: string
  error?: string
}

// =============================================================================
// WEBHOOKS
// =============================================================================

export type WebhookEventType =
  | 'state.updated'
  | 'checkpoint.passed'
  | 'checkpoint.failed'
  | 'document.generated'
  | 'security.scan_completed'
  | 'dsr.received'
  | 'breach.detected'

export interface WebhookConfig {
  id: string
  url: string
  events: WebhookEventType[]
  secret?: string
  enabled: boolean
  createdAt: Date
  updatedAt: Date
}

export interface WebhookPayload {
  id: string
  event: WebhookEventType
  timestamp: string
  tenantId: string
  data: Record<string, unknown>
}

// =============================================================================
// HEALTH & STATUS
// =============================================================================

export interface HealthCheckResponse {
  status: 'healthy' | 'degraded' | 'unhealthy'
  version: string
  uptime: number
  services: Record<string, {
    status: 'up' | 'down'
    latencyMs?: number
  }>
}

export interface RateLimitInfo {
  limit: number
  remaining: number
  resetAt: Date
}
