// src/stores/userListStore.js
import { defineStore } from 'pinia'
import api from 'src/services/api'

export const useUserListStore = defineStore('userlist', {
  state: () => ({
    users: [],
    loading: false,
    error: null,

    filters: {
      search: '',
      onlyActive: false
    }
  }),

  getters: {
    filteredUsers(state) {
      let result = state.users
      const term = state.filters.search?.toLowerCase() || ''

      if (term) {
        result = result.filter(u =>
          u.code?.toLowerCase().includes(term) ||
          u.nebim_username?.toLowerCase().includes(term) ||
          u.role_names?.toLowerCase().includes(term) ||
          u.department_names?.toLowerCase().includes(term) ||
          u.piyasa_names?.toLowerCase().includes(term)
        )
      }

      if (state.filters.onlyActive) {
        result = result.filter(u => u.is_active)
      }

      return result
    }
  },

  actions: {
    async fetchUsers() {
      this.loading = true
      this.error = null

      try {
        const params = {}

        if (this.filters.search) {
          params.search = this.filters.search
        }

        const { data } = await api.get(
          '/users/list',
          { params }
        )

        this.users = Array.isArray(data) ? data : []

        console.log('✅ User listesi alındı:', this.users.length)

      } catch (err) {
        console.error('❌ User listesi alınamadı:', err)
        this.users = []
        this.error =
          err?.message ||
          'Kullanıcı listesi alınamadı'
      } finally {
        this.loading = false
      }
    }
  }
})
