import type { DebugContext } from '../../playground/response-viewer'
import type { HTTPMethod } from '@/lib/api-docs/types'

// Card type identifiers
export type CardType = 'debug_context' | 'response_options' | 'endpoint_context'

// Error types for response options
export type ErrorType = 
  | 'auth' 
  | 'missing_params' 
  | 'invalid_body' 
  | 'missing_headers' 
  | 'validation' 
  | 'not_found' 
  | 'server' 
  | 'generic'

// Base interface for all cards
export interface BaseCardData {
  type: CardType
}

// Debug context card data
export interface DebugContextCardData extends BaseCardData {
  type: 'debug_context'
  context: DebugContext
}

// Response options card data
export interface ResponseOptionsCardData extends BaseCardData {
  type: 'response_options'
  errorType: ErrorType
}

// Endpoint context card data
export interface EndpointContextCardData extends BaseCardData {
  type: 'endpoint_context'
  endpoint: {
    id: string
    name: string
    method: HTTPMethod
    path: string
    description?: string | null
  }
}

// Union type for all card data
export type CardData = DebugContextCardData | ResponseOptionsCardData | EndpointContextCardData

// Card action callbacks
export interface CardActions {
  onOpenGlobalAuth?: () => void
  onNavigateToAuthTab?: () => void
  onNavigateToParamsTab?: () => void
  onNavigateToBodyTab?: () => void
  onNavigateToHeadersTab?: () => void
}

// Prefix used to identify card messages
export const CARD_MESSAGE_PREFIX = '__CARD__'

// Helper to encode card data into a message
export function encodeCardMessage(data: CardData): string {
  return `${CARD_MESSAGE_PREFIX}${JSON.stringify(data)}`
}

// Helper to decode card data from a message
export function decodeCardMessage(content: string): CardData | null {
  if (!content?.startsWith(CARD_MESSAGE_PREFIX)) {
    return null
  }
  
  try {
    const json = content.slice(CARD_MESSAGE_PREFIX.length)
    return JSON.parse(json) as CardData
  } catch {
    return null
  }
}

// Check if a message is a card message
export function isCardMessage(content: string): boolean {
  return content?.startsWith(CARD_MESSAGE_PREFIX) ?? false
}
