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

let lastRequestId = 0

const ACTION_CANONICAL = {
  view: 'read',
  insert: 'write'
}

function normalizeToken(v) {
  return String(v || '').toLowerCase().trim()
}

function canonicalAction(v) {
  const key = normalizeToken(v)
  return ACTION_CANONICAL[key] || key
}

export const useRoleDeptPermissionListStore = defineStore('roleDeptPermissionList', {
  state: () => ({
    modules: [],
    moduleActions: [],
    rows: [],
    loading: false,
    error: null,
    filters: {
      search: ''
    }
  }),

  getters: {
    totalCount (state) {
      return state.rows.length
    }
  },

  actions: {
    async fetchRows () {
      const rid = ++lastRequestId
      this.loading = true
      this.error = null

      try {
        const search = String(this.filters.search || '').trim()
        const params = {}
        if (search) params.search = search

        const res = await api.get('/role-dept-permissions/list', { params })

        if (rid !== lastRequestId) {
          return
        }

        const payload = res?.data || {}
        this.modules = Array.isArray(payload?.modules)
          ? payload.modules.map((m) => ({
            value: String(m.value || '').toLowerCase().trim(),
            label: String(m.label || '')
          })).filter((m) => m.value)
          : []

        this.moduleActions = Array.isArray(payload?.module_actions)
          ? payload.module_actions
            .map((a) => ({
              module_code: normalizeToken(a.module_code),
              action: canonicalAction(a.action)
            }))
            .filter((a) => a.module_code && a.action)
            .filter((a, idx, arr) =>
              arr.findIndex((x) => x.module_code === a.module_code && x.action === a.action) === idx
            )
          : []

        const rawRows = Array.isArray(payload?.rows)
          ? payload.rows
          : Array.isArray(res?.data) ? res.data : []

        this.rows = rawRows.map((r) => {
          const rawFlags = (r?.module_flags && typeof r.module_flags === 'object')
            ? r.module_flags
            : {}
          const flags = {}
          Object.keys(rawFlags).forEach((k) => {
            const [moduleRaw, actionRaw] = normalizeToken(k).split('|')
            if (!moduleRaw || !actionRaw) return
            const action = canonicalAction(actionRaw)
            const key = `${moduleRaw}|${action}`
            flags[key] = Boolean(flags[key]) || Boolean(rawFlags[k])
          })

          return {
            role_id: Number(r.role_id || 0),
            role_title: r.role_title || '',
            department_code: r.department_code || '',
            department_title: r.department_title || '',
            module_flags: flags,
            members: Array.isArray(r.members)
              ? r.members.map((member) => ({
                id: Number(member?.id || 0),
                full_name: String(member?.full_name || ''),
                username: String(member?.username || '')
              })).filter((member) => member.id > 0)
              : []
          }
        })
      } catch (err) {
        if (rid !== lastRequestId) return
        this.modules = []
        this.moduleActions = []
        this.rows = []
        this.error =
          err?.response?.data ||
          err?.message ||
          'Yetki listesi alınamadı'
      } finally {
        if (rid === lastRequestId) {
          this.loading = false
        }
      }
    }
  }
})
