// src/client/entities/access.ts
// Access entity - Pinia store for external access management

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { ExternalAccess, CreateAccessRequest, UpdateAccessRequest } from '@shared/contracts/access';

// Re-export types for backward compatibility
export type Access = ExternalAccess;
export type CreateAccessInput = CreateAccessRequest;
export type UpdateAccessInput = UpdateAccessRequest;

export const useAccessStore = defineStore('access', () => {
  // State
  const items = ref<Access[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // Computed
  const activeItems = computed(() => items.value);

  // Actions
  async function fetchAll() {
    loading.value = true;
    error.value = null;
    try {
      // AccessRepository будет создан на следующем шаге
      const { accessRepository } = await import('../shared/api/repositories/AccessRepository');
      const data = await accessRepository.getAll();
      items.value = data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить внешние доступы';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchById(id: string) {
    loading.value = true;
    error.value = null;
    try {
      const { accessRepository } = await import('../shared/api/repositories/AccessRepository');
      const data = await accessRepository.getById(id);
      // Smart Merge: update item in array without full refetch
      const index = items.value.findIndex((item: Access) => item.id === id);
      if (index >= 0) {
        items.value[index] = data;
      } else {
        items.value.push(data);
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function create(input: CreateAccessInput) {
    loading.value = true;
    error.value = null;
    try {
      const { accessRepository } = await import('../shared/api/repositories/AccessRepository');
      const data = await accessRepository.create(input);
      items.value.push(data);
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось создать запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function update(id: string, input: UpdateAccessInput) {
    loading.value = true;
    error.value = null;
    try {
      const { accessRepository } = await import('../shared/api/repositories/AccessRepository');
      const data = await accessRepository.update(id, input);
      // Smart Merge: update item in array without full refetch
      const index = items.value.findIndex((item: Access) => item.id === id);
      if (index >= 0) {
        items.value[index] = data;
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось обновить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function remove(id: string) {
    loading.value = true;
    error.value = null;
    try {
      const { accessRepository } = await import('../shared/api/repositories/AccessRepository');
      await accessRepository.deleteEntry(id);
      // Remove item from array
      const index = items.value.findIndex((item: Access) => item.id === id);
      if (index >= 0) {
        items.value.splice(index, 1);
      }
    } catch (err: any) {
      error.value = err.message || 'Не удалось удалить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  /**
   * Smart Merge: update single item in array without full refetch
   * Preserves UI state (scroll position, filters, etc.)
   */
  function smartMergeItem(item: Access) {
    const index = items.value.findIndex((i: Access) => i.id === item.id);
    if (index >= 0) {
      items.value[index] = item;
    } else {
      items.value.push(item);
    }
  }

  /**
   * Remove item from state
   */
  function removeItem(id: string) {
    const index = items.value.findIndex((item: Access) => item.id === id);
    if (index >= 0) {
      items.value.splice(index, 1);
    }
  }

  function clearError() {
    error.value = null;
  }

  return {
    // State
    items,
    loading,
    error,
    // Computed
    activeItems,
    // Actions
    fetchAll,
    fetchById,
    create,
    update,
    remove,
    clearError,
    // Smart Merge methods (for socket updates)
    smartMergeItem,
    removeItem,
  };
});
