import { api } from '@/utils/request'

export interface RoleRecord {
  id: number
  name: string
  label: string
  description: string
  users_count: number
  route_groups_count: number
}

export interface RouteOverride {
  route_id: number
  method: string
  path: string
  allowed: boolean
}

export const useRoleManageStore = defineStore('role-manage', () => {
  const roles = ref<RoleRecord[]>([])
  const loading = ref(false)

  async function fetchRoles() {
    loading.value = true
    try {
      const data = await api.get<RoleRecord[]>('/api/v1/roles')
      roles.value = data
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '获取角色列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  async function fetchRoleRouteGroups(roleId: number) {
    const data = await api.get<{ id: number }[]>(`/api/v1/roles/${roleId}/route-groups`)
    return data.map((g) => g.id)
  }

  async function setRoleRouteGroups(roleId: number, groupIds: number[]) {
    await api.put(`/api/v1/roles/${roleId}/route-groups`, { group_ids: groupIds })
  }

  async function fetchRoleOverrides(roleId: number) {
    const data = await api.get<RouteOverride[]>(`/api/v1/roles/${roleId}/route-overrides`)
    return data
  }

  async function setRoleOverrides(roleId: number, overrides: RouteOverride[]) {
    await api.put(`/api/v1/roles/${roleId}/route-overrides`, { overrides })
  }

  return {
    roles,
    loading,
    fetchRoles,
    fetchRoleRouteGroups,
    setRoleRouteGroups,
    fetchRoleOverrides,
    setRoleOverrides,
  }
})
