import { create } from 'zustand';
import { storage } from '../infrastructure/storage';

interface ConfigState {
  apiUrl: string;
  updateUrl: string;
  isConfigured: boolean;
  setUrls: (apiUrl: string, updateUrl: string) => void;
  initialize: () => void;
}

const DEFAULT_API_URL = 'https://mess.khomegeneric.keenetic.pro/api';
const DEFAULT_UPDATE_URL = 'https://mess.khomegeneric.keenetic.pro/api/v1/updates';

export const useConfigStore = create<ConfigState>((set) => ({
  apiUrl: DEFAULT_API_URL,
  updateUrl: DEFAULT_UPDATE_URL,
  isConfigured: false,

  initialize: () => {
    const savedApiUrl = storage.getString('config_api_url');
    const savedUpdateUrl = storage.getString('config_update_url');
    const configured = storage.getBoolean('config_is_configured');

    if (savedApiUrl && savedUpdateUrl) {
      set({ 
        apiUrl: savedApiUrl, 
        updateUrl: savedUpdateUrl, 
        isConfigured: !!configured 
      });
    }
  },

  setUrls: (apiUrl: string, updateUrl: string) => {
    storage.set('config_api_url', apiUrl);
    storage.set('config_update_url', updateUrl);
    storage.set('config_is_configured', true);
    set({ apiUrl, updateUrl, isConfigured: true });
  },
}));
