// src/client/entities/equipment.ts
// Equipment entity - types and store for local IT, security, and other equipment management

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import {
  localITRepository,
  localSecurityRepository,
  otherEquipmentRepository,
  type LocalITResponse,
  type CreateLocalITRequest,
  type UpdateLocalITRequest,
  type LocalSecurityResponse,
  type CreateLocalSecurityRequest,
  type UpdateLocalSecurityRequest,
  type OtherEquipmentResponse,
  type CreateOtherEquipmentRequest,
  type UpdateOtherEquipmentRequest,
} from '../shared/api/repositories/EquipmentRepository';

// Re-export types for backward compatibility
export type LocalIT = LocalITResponse;
export type CreateLocalITInput = CreateLocalITRequest;
export type UpdateLocalITInput = UpdateLocalITRequest;
export type LocalSecurity = LocalSecurityResponse;
export type CreateLocalSecurityInput = CreateLocalSecurityRequest;
export type UpdateLocalSecurityInput = UpdateLocalSecurityRequest;
export type OtherEquipment = OtherEquipmentResponse;
export type CreateOtherEquipmentInput = CreateOtherEquipmentRequest;
export type UpdateOtherEquipmentInput = UpdateOtherEquipmentRequest;

export type EquipmentCategory = 'it' | 'security' | 'other';

export const useEquipmentStore = defineStore('equipment', () => {
  // State
  const localITItems = ref<LocalIT[]>([]);
  const localSecurityItems = ref<LocalSecurity[]>([]);
  const otherEquipmentItems = ref<OtherEquipment[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // Computed
  const activeLocalITItems = computed(() => localITItems.value);
  const activeLocalSecurityItems = computed(() => localSecurityItems.value);
  const activeOtherEquipmentItems = computed(() => otherEquipmentItems.value);

  // ============ LOCAL IT ACTIONS ============

  async function fetchAllLocalIT() {
    loading.value = true;
    error.value = null;
    try {
      const data = await localITRepository.getAll();
      localITItems.value = data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить IT оборудование';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchLocalITById(id: string) {
    loading.value = true;
    error.value = null;
    try {
      const data = await localITRepository.getById(id);
      // Smart Merge: Update or add item to list
      const index = localITItems.value.findIndex((item: LocalIT) => item.id === id);
      if (index >= 0) {
        localITItems.value[index] = data;
      } else {
        localITItems.value.push(data);
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createLocalIT(input: CreateLocalITInput) {
    loading.value = true;
    error.value = null;
    try {
      const data = await localITRepository.create(input);
      localITItems.value.push(data);
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось создать запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateLocalIT(id: string, input: UpdateLocalITInput) {
    loading.value = true;
    error.value = null;
    try {
      const data = await localITRepository.update(id, input);
      // Smart Merge: Update only the changed item
      const index = localITItems.value.findIndex((item: LocalIT) => item.id === id);
      if (index >= 0) {
        localITItems.value[index] = data;
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось обновить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function archiveLocalIT(id: string) {
    loading.value = true;
    error.value = null;
    try {
      await localITRepository.archive(id);
      const index = localITItems.value.findIndex((item: LocalIT) => item.id === id);
      if (index >= 0) {
        localITItems.value.splice(index, 1);
      }
    } catch (err: any) {
      error.value = err.message || 'Не удалось архивировать запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // ============ LOCAL SECURITY ACTIONS ============

  async function fetchAllLocalSecurity() {
    loading.value = true;
    error.value = null;
    try {
      const data = await localSecurityRepository.getAll();
      localSecurityItems.value = data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить оборудование ОПС';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchLocalSecurityById(id: string) {
    loading.value = true;
    error.value = null;
    try {
      const data = await localSecurityRepository.getById(id);
      // Smart Merge: Update or add item to list
      const index = localSecurityItems.value.findIndex((item: LocalSecurity) => item.id === id);
      if (index >= 0) {
        localSecurityItems.value[index] = data;
      } else {
        localSecurityItems.value.push(data);
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createLocalSecurity(input: CreateLocalSecurityInput) {
    loading.value = true;
    error.value = null;
    try {
      const data = await localSecurityRepository.create(input);
      localSecurityItems.value.push(data);
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось создать запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateLocalSecurity(id: string, input: UpdateLocalSecurityInput) {
    loading.value = true;
    error.value = null;
    try {
      const data = await localSecurityRepository.update(id, input);
      // Smart Merge: Update only the changed item
      const index = localSecurityItems.value.findIndex((item: LocalSecurity) => item.id === id);
      if (index >= 0) {
        localSecurityItems.value[index] = data;
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось обновить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function archiveLocalSecurity(id: string) {
    loading.value = true;
    error.value = null;
    try {
      await localSecurityRepository.archive(id);
      const index = localSecurityItems.value.findIndex((item: LocalSecurity) => item.id === id);
      if (index >= 0) {
        localSecurityItems.value.splice(index, 1);
      }
    } catch (err: any) {
      error.value = err.message || 'Не удалось архивировать запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // ============ OTHER EQUIPMENT ACTIONS ============

  async function fetchAllOtherEquipment() {
    loading.value = true;
    error.value = null;
    try {
      const data = await otherEquipmentRepository.getAll();
      otherEquipmentItems.value = data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить прочее оборудование';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchOtherEquipmentById(id: string) {
    loading.value = true;
    error.value = null;
    try {
      const data = await otherEquipmentRepository.getById(id);
      // Smart Merge: Update or add item to list
      const index = otherEquipmentItems.value.findIndex((item: OtherEquipment) => item.id === id);
      if (index >= 0) {
        otherEquipmentItems.value[index] = data;
      } else {
        otherEquipmentItems.value.push(data);
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось загрузить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createOtherEquipment(input: CreateOtherEquipmentInput) {
    loading.value = true;
    error.value = null;
    try {
      const data = await otherEquipmentRepository.create(input);
      otherEquipmentItems.value.push(data);
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось создать запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateOtherEquipment(id: string, input: UpdateOtherEquipmentInput) {
    loading.value = true;
    error.value = null;
    try {
      const data = await otherEquipmentRepository.update(id, input);
      // Smart Merge: Update only the changed item
      const index = otherEquipmentItems.value.findIndex((item: OtherEquipment) => item.id === id);
      if (index >= 0) {
        otherEquipmentItems.value[index] = data;
      }
      return data;
    } catch (err: any) {
      error.value = err.message || 'Не удалось обновить запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function archiveOtherEquipment(id: string) {
    loading.value = true;
    error.value = null;
    try {
      await otherEquipmentRepository.archive(id);
      const index = otherEquipmentItems.value.findIndex((item: OtherEquipment) => item.id === id);
      if (index >= 0) {
        otherEquipmentItems.value.splice(index, 1);
      }
    } catch (err: any) {
      error.value = err.message || 'Не удалось архивировать запись';
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // ============ COMMON ACTIONS ============

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

  return {
    // State
    localITItems,
    localSecurityItems,
    otherEquipmentItems,
    loading,
    error,
    // Computed
    activeLocalITItems,
    activeLocalSecurityItems,
    activeOtherEquipmentItems,
    // Local IT Actions
    fetchAllLocalIT,
    fetchLocalITById,
    createLocalIT,
    updateLocalIT,
    archiveLocalIT,
    // Local Security Actions
    fetchAllLocalSecurity,
    fetchLocalSecurityById,
    createLocalSecurity,
    updateLocalSecurity,
    archiveLocalSecurity,
    // Other Equipment Actions
    fetchAllOtherEquipment,
    fetchOtherEquipmentById,
    createOtherEquipment,
    updateOtherEquipment,
    archiveOtherEquipment,
    // Common Actions
    clearError,
  };
});
