/**
 * Unified API Response Format
 *
 * Provides consistent response structure across all webshop API endpoints
 * for Shopify, WooCommerce, and ShopRenter platforms.
 *
 * Related: Issue #53 - Unified webshop API response format
 */

// ============================================================================
// Response Type Definitions
// ============================================================================

export interface UnifiedResponseMetadata {
  /** Platform name (shopify, woocommerce, shoprenter) - only for data endpoints */
  platform?: string;
  /** Store UUID - only for data endpoints */
  store_id?: string;
  /** Resource type being accessed */
  resource_type: "customers" | "orders" | "products" | "stores";
  /** Authentication type used */
  auth_type: "user" | "internal";
  /** ISO 8601 timestamp when data was fetched */
  fetched_at: string;
  /** Optional request tracking ID */
  request_id?: string;
}

export interface UnifiedPagination {
  /** Current page number (1-indexed) */
  page: number;
  /** Items per page limit */
  limit: number;
  /** Total count of items (if available from platform) */
  total?: number;
  /** Whether there are more items after this page */
  has_more: boolean;
  /** Next page number (null if no more pages) */
  next_page: number | null;
  /** Previous page number (null if first page) */
  prev_page: number | null;
}

export interface UnifiedErrorDetails {
  /** Error code for programmatic handling */
  code: string;
  /** Human-readable error message */
  message: string;
  /** Additional error details */
  details?: unknown;
}

export interface UnifiedApiResponse<T> {
  /** Whether the request was successful */
  success: boolean;
  /** Response data (single item or array) */
  data: T | T[];
  /** Response metadata */
  metadata: UnifiedResponseMetadata;
  /** Pagination information (only for list endpoints) */
  pagination?: UnifiedPagination;
  /** Error information (only when success=false) */
  error?: UnifiedErrorDetails;
}

// ============================================================================
// Response Builder Functions
// ============================================================================

/**
 * Create a successful response for a single item
 */
export function createSuccessResponse<T>(
  data: T,
  metadata: UnifiedResponseMetadata
): UnifiedApiResponse<T> {
  return {
    success: true,
    data,
    metadata: {
      ...metadata,
      fetched_at: new Date().toISOString(),
    },
  };
}

/**
 * Create a successful response for a list of items with pagination
 */
export function createListResponse<T>(
  data: T[],
  metadata: UnifiedResponseMetadata,
  pagination: {
    page: number;
    limit: number;
    total?: number;
    has_more: boolean;
  }
): UnifiedApiResponse<T> {
  const { page, limit, total, has_more } = pagination;

  return {
    success: true,
    data,
    metadata: {
      ...metadata,
      fetched_at: new Date().toISOString(),
    },
    pagination: {
      page,
      limit,
      total,
      has_more,
      next_page: has_more ? page + 1 : null,
      prev_page: page > 1 ? page - 1 : null,
    },
  };
}

/**
 * Create an error response
 */
export function createErrorResponse(
  code: string,
  message: string,
  details?: unknown,
  status: number = 500
): Response {
  const response: UnifiedApiResponse<never> = {
    success: false,
    data: [] as never,
    metadata: {
      resource_type: "stores" as const,
      auth_type: "user",
      fetched_at: new Date().toISOString(),
    },
    error: {
      code,
      message,
      details,
    },
  };

  return new Response(JSON.stringify(response), {
    status,
    headers: { "Content-Type": "application/json" },
  });
}

/**
 * Create a unified Response object from a unified response
 */
export function toHttpResponse<T>(
  response: UnifiedApiResponse<T>,
  status: number = 200
): Response {
  return new Response(JSON.stringify(response), {
    status,
    headers: { "Content-Type": "application/json" },
  });
}

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Calculate pagination has_more based on returned items
 */
export function calculateHasMore(
  returnedCount: number,
  requestedLimit: number
): boolean {
  return returnedCount === requestedLimit;
}

/**
 * Generate a unique request ID for tracking
 */
export function generateRequestId(): string {
  return `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
}
