import { create } from 'zustand';
import { api } from './api';

const ERR_INVALID_RESPONSE_FORMAT = 'errors.invalidResponseFormat';
const ERR_UNKNOWN = 'errors.unknownError';

interface Plan {
  _id?: string;
  id?: string;
  name: string;
  period: string;
  price: number;
  description?: string;
  features?: string[];
  [key: string]: any;
}

interface PlansState {
  plans: Plan[];
  isLoading: boolean;
  error: string | null;
  fetchPlans: () => Promise<void>;
  getPlanById: (id: string) => Plan | undefined;
  resetPlans: () => void;
}

export const usePlansStore = create<PlansState>((set, get) => ({
  plans: [],
  isLoading: false,
  error: null,

  fetchPlans: async () => {
    const { plans } = get();
    
    // If plans already loaded, don't fetch again
    if (plans.length > 0) {
      return;
    }

    set({ isLoading: true, error: null });
    
    try {
      const res = await api.subscription.getPlans();

      if (res.success && Array.isArray(res.data)) {
        set({ plans: res.data, isLoading: false, error: null });
        return;
      }

      set({
        isLoading: false,
        error: res.error || ERR_INVALID_RESPONSE_FORMAT,
        plans: []
      });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : ERR_UNKNOWN;
      set({
        isLoading: false,
        error: errorMessage,
        plans: []
      });
    }
  },

  getPlanById: (id: string) => {
    const { plans } = get();
    return plans.find(plan => plan._id === id || plan.id === id);
  },

  resetPlans: () => {
    set({ plans: [], isLoading: false, error: null });
  },
}));
