/**
 * Rate Limit Store
 * Action 5.4.1.1: Store rate limit state from API response headers
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

/**
 * Rate limit state from API headers
 */
export interface RateLimitState {
  /** Maximum number of requests allowed */
  limit: number | null;
  /** Number of requests remaining */
  remaining: number | null;
  /** Unix timestamp when the rate limit resets */
  reset: number | null;
  /** Number of seconds to wait before retrying (for 429 errors) */
  retryAfter: number | null;
  /** Whether the user is currently rate limited */
  isLimited: boolean;
  /** Last time rate limit headers were updated */
  lastUpdated: number | null;
}

interface RateLimitActions {
  /** Update rate limit state from headers */
  updateRateLimit: (headers: {
    limit?: string | number | null;
    remaining?: string | number | null;
    reset?: string | number | null;
    retryAfter?: string | number | null;
  }) => void;
  /** Clear rate limit state */
  clearRateLimit: () => void;
}

const initialState: RateLimitState = {
  limit: null,
  remaining: null,
  reset: null,
  retryAfter: null,
  isLimited: false,
  lastUpdated: null,
};

export const useRateLimitStore = create<RateLimitState & RateLimitActions>()(
  persist(
    (set) => ({
      ...initialState,
      updateRateLimit: (headers) => {
        const limit =
          headers.limit !== null && headers.limit !== undefined
            ? typeof headers.limit === 'string'
              ? parseInt(headers.limit, 10)
              : headers.limit
            : null;

        const remaining =
          headers.remaining !== null && headers.remaining !== undefined
            ? typeof headers.remaining === 'string'
              ? parseInt(headers.remaining, 10)
              : headers.remaining
            : null;

        const reset =
          headers.reset !== null && headers.reset !== undefined
            ? typeof headers.reset === 'string'
              ? parseInt(headers.reset, 10)
              : headers.reset
            : null;

        const retryAfter =
          headers.retryAfter !== null && headers.retryAfter !== undefined
            ? typeof headers.retryAfter === 'string'
              ? parseInt(headers.retryAfter, 10)
              : headers.retryAfter
            : null;

        // Determine if rate limited (remaining is 0 or retryAfter is set)
        const isLimited =
          (remaining !== null && remaining <= 0) || retryAfter !== null;

        set({
          limit,
          remaining,
          reset,
          retryAfter,
          isLimited,
          lastUpdated: Date.now(),
        });
      },
      clearRateLimit: () => {
        set(initialState);
      },
    }),
    {
      name: 'rate-limit-storage',
      // Only persist essential state, not timestamps
      partialize: (state) => ({
        limit: state.limit,
        remaining: state.remaining,
        reset: state.reset,
        retryAfter: state.retryAfter,
        isLimited: state.isLimited,
        lastUpdated: null, // Don't persist timestamp
      }),
    },
  ),
);
