import { z } from 'zod';

/**
 * Base interface for navigation context data.
 * Extend this interface for type-safe context preservation.
 *
 * @example
 * ```typescript
 * interface MyFlowContext extends NavigationContextData {
 *   returnUrl: string;
 *   selectedItems: number[];
 * }
 * ```
 */
export interface NavigationContextData {
  [key: string]: unknown;
}

/**
 * Navigation context stored in tab metadata.
 * Represents a single preserved navigation state with metadata.
 * Stored at: tab.metadata[NAVIGATION_CONTEXT_METADATA_KEY][customScope]
 */
export interface NavigationContext {
  /** The preserved navigation state/data */
  data: NavigationContextData;
  /** Timestamp when context was created (for debugging and monitoring) */
  createdAt: number;
  /**
   * Optional expiration timestamp (reserved for future TTL implementation)
   * @deprecated Currently unused - contexts are cleaned up automatically when tabs close
   */
  expiresAt?: number;
}

/**
 * Zod schema for navigation context data validation.
 */
export const NavigationContextDataSchema = z.record(z.string(), z.unknown());

/**
 * Zod schema for navigation context validation.
 */
export const NavigationContextSchema = z.object({
  data: NavigationContextDataSchema,
  createdAt: z.number().positive(),
  expiresAt: z.number().positive().optional(),
});

/**
 * Zod schema for navigation contexts stored in tab metadata.
 * Structure: { [customScope: string]: NavigationContext }
 *
 * @example
 * ```typescript
 * {
 *   "default": { data: { returnUrl: '/cart' }, createdAt: 123, expiresAt: 456 },
 *   "customer-details": { data: { customerId: 42 }, createdAt: 123 }
 * }
 * ```
 */
export const NavigationContextsMetadataSchema = z.record(
  z.string(),
  NavigationContextSchema
);

/**
 * Common navigation context for "return URL" pattern.
 * Used when navigating through a flow and needing to return to the original location.
 *
 * @example
 * ```typescript
 * navContextService.preserveContext({
 *   returnUrl: '/original-page'
 * });
 * ```
 */
export interface ReturnUrlContext extends NavigationContextData {
  returnUrl: string;
}

/**
 * Extended context with additional flow metadata.
 * Useful for complex multi-step flows that need to preserve additional state.
 *
 * @example
 * ```typescript
 * interface CheckoutFlowContext extends FlowContext {
 *   returnUrl: string;
 *   selectedProductIds: number[];
 *   shippingAddressId?: number;
 * }
 * ```
 */
export interface FlowContext extends NavigationContextData {
  /** Step identifier for multi-step flows */
  currentStep?: string;
  /** Total number of steps (if known) */
  totalSteps?: number;
  /** Flow-specific metadata */
  metadata?: Record<string, unknown>;
}
