import { defineStore } from 'pinia';
import { ref } from 'vue';
import axios from 'boot/axios';
import { Dark } from 'quasar';

export const usePreferencesStore = defineStore('preferences', () =>
{
  // Grouped user preferences structure (can be imported/shared if needed)
  const preferences = ref({
    UI: [
      {
        name: 'Theme',
        key: 'theme',
        type: 'text',
        options: [
          { label: 'Light', value: 'light' },
          { label: 'Dark', value: 'dark' },
        ],
      },
    ],
    API_Tokens: [
      {
        name: 'Mantis API Key',
        key: 'MANTIS_API_KEY',
        type: 'text',
      }
    ]
  });

  const values = ref({});
  const loading = ref(false);
  const saving = ref(false);
  const error = ref(null);

  async function loadPreferences()
  {
    loading.value = true;
    error.value = null;
    values.value = {};
    const allKeys = Object.values(preferences.value).flat().map(p => p.key);
    try
    {
      const responses = await Promise.all(
        allKeys.map(key =>
          axios.get(`/api/user-preferences/${key}`, {
            validateStatus: status => status === 200 || status === 404,
          })
        )
      );
      responses.forEach((response, idx) =>
      {
        const key = allKeys[idx];
        if (response.status === 404)
        {
          values.value[key] = '';
        }
        else
        {
          values.value[key] = response.data.value;
        }
      });
    }
    catch (err)
    {
      error.value = err.response?.data?.error || 'Failed to load preferences.';
    }
    finally
    {
      loading.value = false;
    }

    //If we have a "theme" preference, change it in Quasar
    if (values.value.theme)
    {
      Dark.set(values.value.theme === 'dark');
    }
  }

  async function savePreferences()
  {
    saving.value = true;
    error.value = null;
    const allKeys = Object.keys(values.value);
    const requests = allKeys.map(key =>
      axios.put(`/api/user-preferences/${key}`, { value: values.value[key] })
    );
    try
    {
      await Promise.all(requests);
    }
    catch (err)
    {
      error.value = err.response?.data?.error || 'Failed to save preferences.';
    }
    finally
    {
      saving.value = false;
    }

    if (values.value.theme)
    {
      Dark.set(values.value.theme === 'dark');
    }
  }

  return {
    preferences,
    values,
    loading,
    saving,
    error,
    loadPreferences,
    savePreferences,
  };
});
