import { defineStore } from 'pinia'
import api from '../axios'

export const useUsuariosStore = defineStore('usuarios', {
  state: () => ({
    usuarios: [],
    roles: [],
    loading: false,
    pagination: {
      current: 1,
      pageSize: 15,
      total: 0,
    },
  }),

  actions: {
    async fetchUsuarios(params = {}) {
      this.loading = true
      try {
        const response = await api.get('/admin/usuarios', { params })
        const { data } = response.data
        this.usuarios = data.data
        this.pagination = {
          current: data.current_page,
          pageSize: data.per_page,
          total: data.total,
        }
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchRoles() {
      try {
        const response = await api.get('/admin/roles')
        this.roles = response.data.data
      } catch (error) {
        throw error
      }
    },

    async createUsuario(payload) {
      const response = await api.post('/admin/usuarios', payload)
      return response.data
    },

    async updateUsuario(id, payload) {
      const response = await api.put(`/admin/usuarios/${id}`, payload)
      return response.data
    },

    async changePassword(id, payload) {
      const response = await api.patch(`/admin/usuarios/${id}/cambiar-password`, payload)
      return response.data
    },

    async deleteUsuario(id) {
      const response = await api.delete(`/admin/usuarios/${id}`)
      return response.data
    },
  },
})
