import { defineStore } from 'pinia'
import { get } from 'src/services/api'

export const useActivityLogStore = defineStore('activityLogStore', {
  state: () => ({
    loading: false,
    rows: [],
    total: 0,
    pagination: {
      page: 1,
      rowsPerPage: 1000,
      rowsNumber: 0,
      sortBy: 'created_at',
      descending: true
    },
    filters: {
      username: '',
      actionCategory: null,
      actionType: '',
      success: null,
      dateFrom: '',
      dateTo: ''
    }
  }),

  actions: {
    async fetchLogs () {
      this.loading = true
      try {
        const params = {
          page: Math.max(1, Number(this.pagination.page || 1)),
          limit: Math.min(1000, Math.max(1, Number(this.pagination.rowsPerPage || 1000)))
        }

        if (this.filters.username) params.username = this.filters.username
        if (this.filters.actionCategory) params.action_category = this.filters.actionCategory
        if (this.filters.actionType) params.action_type = this.filters.actionType
        if (this.filters.success !== null) params.success = this.filters.success
        if (this.filters.dateFrom) params.date_from = this.filters.dateFrom
        if (this.filters.dateTo) params.date_to = this.filters.dateTo

        const data = await get('/activity-logs', params)

        this.rows = data.items || []
        this.total = data.total || 0
        this.pagination.rowsNumber = this.total
      } finally {
        this.loading = false
      }
    },

    quickRoleChange () {
      this.filters.actionCategory = 'role_permission'
      this.filters.actionType = 'role_department_permission_change'
      this.pagination.page = 1
      this.fetchLogs()
    },

    onTableRequest (props) {
      const { page, rowsPerPage, sortBy, descending } = props.pagination

      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending

      this.fetchLogs()
    },

    resetFilters () {
      this.filters = {
        username: '',
        actionCategory: null,
        actionType: '',
        success: null,
        dateFrom: '',
        dateTo: ''
      }
      this.pagination.page = 1
      this.fetchLogs()
    }
  }
})
