// stores/RoleStore.js
import {defineStore} from 'pinia'
import {roleService} from '@/api/roleService'


export const useRoleStore = defineStore('role', {
    state: () => ({
        roles: [],         // [{id, name, permissions: [...]}, …]
        permissions: [],   // [{id, name}, …]
    }),
    actions: {
        async fetchRoles() {
            try {
                const res = await roleService.getRoles()
                this.roles = res.data
            } catch (e) {
                console.error('fetchRoles error', e)
            }
        },
        async fetchPermissions() {
            try {
                const res = await roleService.getPermissions()
                this.permissions = res.data
            } catch (e) {
                console.error('fetchPermissions error', e)
            }
        },
        async addPermission(name) {
            try {
                const res = await roleService.createPermission({name})
                this.permissions.push(res.data)
            } catch (e) {
                console.error('addPermission error', e)
                throw e
            }
        },
        async removePermission(id) {
            try {
                await roleService.deletePermission(id)
                this.permissions = this.permissions.filter(p => p.id !== id)
                this.roles.forEach(r => {
                    r.permissions = r.permissions.filter(p => p.id !== id)
                })
            } catch (e) {
                console.error('removePermission error', e)
            }
        },
        async toggleRolePermission(roleId, permId, assigned) {
            try {
                const role = this.roles.find(r => r.id === roleId)
                if (assigned) {
                    await roleService.attachPermission(roleId, permId)
                    const perm = this.permissions.find(p => p.id === permId)
                    role.permissions.push(perm)
                } else {
                    await roleService.detachPermission(roleId, permId)
                    role.permissions = role.permissions.filter(p => p.id !== permId)
                }
            } catch (e) {
                console.error('toggleRolePermission error', e)
            }
        },
    }
})
