<template>
  <div class="user-rights-view">
    <h1>{{ $t('navigation.m-administration.userrights') }}</h1>

    <AdminUserSearch @select="selectUser" />

    <div v-if="selected" class="editor">
      <h2>{{ selected.username }}</h2>
      <div class="assign">
        <label>{{ $t('admin.rights.add') }}</label>
        <select v-model.number="newRightId">
          <option :value="0">{{ $t('admin.rights.select') }}</option>
          <option v-for="t in rightTypes" :key="t.id" :value="t.id">{{ t.title }}</option>
        </select>
        <button :disabled="!newRightId" @click="addRight">{{ $t('common.add') }}</button>
      </div>

      <h3>{{ $t('admin.rights.current') }}</h3>
      <ul class="rights">
        <li v-for="r in rights" :key="r.rightTypeId">
          {{ r.title }}
          <button class="remove" @click="removeRight(r.rightTypeId)">{{ $t('common.delete') }}</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import apiClient from '@/utils/axios.js';
import AdminUserSearch from '@/components/admin/AdminUserSearch.vue';

export default {
  name: 'UserRightsView',
  components: { AdminUserSearch },
  data() {
    return {
      loading: false,
      selected: null,
      rightTypes: [],
      rights: [],
      newRightId: 0
    };
  },
  async mounted() {
    await this.loadRightTypes();
  }
  ,
  methods: {
    async loadRightTypes() {
      try {
        const res = await apiClient.get('/api/admin/rights/types');
        this.rightTypes = res.data || [];
      } catch (e) {
        console.error('Fehler beim Laden der Rechte-Typen:', e);
      }
    },
    async selectUser(u) {
      this.selected = u;
      const res = await apiClient.get(`/api/admin/rights/${u.id}`);
      this.rights = res.data || [];
      this.newRightId = 0;
    },
    async addRight() {
      if (!this.selected || !this.newRightId) return;
      await apiClient.post(`/api/admin/rights/${this.selected.id}`, { rightTypeId: this.newRightId });
      await this.selectUser(this.selected);
    },
    async removeRight(rightTypeId) {
      if (!this.selected) return;
      await apiClient.delete(`/api/admin/rights/${this.selected.id}`, { data: { rightTypeId } });
      await this.selectUser(this.selected);
    }
  }
};
</script>

<style scoped>
.user-rights-view { padding: 20px; }
.content { margin-top: 10px; }
.loading, .empty { color: #666; }
.rights-table { width: 100%; border-collapse: collapse; }
.rights-table th, .rights-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
.rights-table th { background: #f5f5f5; }
</style>


