import { defineStore } from 'pinia';
import { ref, watch } from 'vue';

export interface KeyValue {
  id: string;
  key: string;
  value: string;
  enabled: boolean;
}

export interface AuthState {
  type: 'none' | 'basic' | 'bearer' | 'api_key';
  basic: { username: '', password: '' };
  bearer: { token: '' };
  apiKey: { key: '', value: '', addTo: 'header' | 'query' };
}

export interface RequestData {
  id: string;
  method: string;
  url: string;
  params: KeyValue[];
  headers: KeyValue[];
  body: string;
  auth: AuthState;
  response?: {
    status: number;
    headers: Record<string, string>;
    body: string;
    time: number;
    size: number;
  };
  timestamp: number;
}

export const useRequestStore = defineStore('request', () => {
  // State
  const history = ref<RequestData[]>([]);
  const activeRequest = ref<RequestData>({
    id: crypto.randomUUID(),
    method: 'GET',
    url: '',
    params: [
        { id: crypto.randomUUID(), key: '', value: '', enabled: true }
    ],
    headers: [
        { id: crypto.randomUUID(), key: '', value: '', enabled: true }
    ],
    body: '',
    auth: {
        type: 'none',
        basic: { username: '', password: '' },
        bearer: { token: '' },
        apiKey: { key: '', value: '', addTo: 'header' }
    },
    timestamp: Date.now(),
  });

  // Load history from local storage
  const savedHistory = localStorage.getItem('request_history');
  if (savedHistory) {
    try {
      history.value = JSON.parse(savedHistory);
    } catch (e) {
      console.error('Failed to parse history', e);
    }
  }

  // Actions
  const addToHistory = (req: RequestData) => {
    // Add to beginning, limit to 50
    const newEntry = { ...req, timestamp: Date.now() };
    // Don't store the empty trailing rows in history to save space? 
    // Actually keep them for consistency or filter them. Let's filter empty keys.
    newEntry.params = newEntry.params.filter(p => p.key.trim() !== '');
    newEntry.headers = newEntry.headers.filter(h => h.key.trim() !== '');
    
    history.value.unshift(newEntry);
    if (history.value.length > 50) {
      history.value.pop();
    }
  };

  const clearHistory = () => {
    history.value = [];
  };

  const deleteHistoryItem = (id: string) => {
    const index = history.value.findIndex(item => item.id === id);
    if (index !== -1) {
      history.value.splice(index, 1);
    }
  };

  const resetActiveRequest = () => {
    activeRequest.value = {
        id: crypto.randomUUID(),
        method: 'GET',
        url: '',
        params: [
            { id: crypto.randomUUID(), key: '', value: '', enabled: true }
        ],
        headers: [
            { id: crypto.randomUUID(), key: '', value: '', enabled: true }
        ],
        body: '',
        auth: {
            type: 'none',
            basic: { username: '', password: '' },
            bearer: { token: '' },
            apiKey: { key: '', value: '', addTo: 'header' }
        },
        timestamp: Date.now(),
    };
  };

  const loadRequest = (req: RequestData) => {
    // Deep copy
    const loaded = JSON.parse(JSON.stringify(req));
    loaded.id = crypto.randomUUID();
    loaded.response = undefined;
    
    // Ensure at least one empty row for editing
    if (loaded.params.length === 0) loaded.params.push({ id: crypto.randomUUID(), key: '', value: '', enabled: true });
    if (loaded.headers.length === 0) loaded.headers.push({ id: crypto.randomUUID(), key: '', value: '', enabled: true });

    // Ensure auth object exists (migration for old history)
    if (!loaded.auth) {
        loaded.auth = {
            type: 'none',
            basic: { username: '', password: '' },
            bearer: { token: '' },
            apiKey: { key: '', value: '', addTo: 'header' }
        };
    }

    activeRequest.value = loaded;
  };

  // Watch and Save
  watch(history, (newVal) => {
    localStorage.setItem('request_history', JSON.stringify(newVal));
  }, { deep: true });

  return {
    history,
    activeRequest,
    addToHistory,
    clearHistory,
    deleteHistoryItem,
    loadRequest,
    resetActiveRequest
  };
});
