<template>
    <UseTabs :student="student" :permissionsByRole="permissionsByRole" />
  </template>
  
  <script>
  import { onMounted, reactive, ref, computed } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { useStudentStore } from '../stores/students';  // Ajuste conforme o local do seu store.
  import UseTabs from '../components/users/UseTabs.vue';  
  
  export default {
    components: {
      UseTabs, // Registra o componente
    },
    setup() {
      const router = useRouter();
      const route = useRoute();
      const studentStore = useStudentStore();
  
      const student = reactive({
        id: null,
        username: '',
        email: '',
        enrollment_number: '',
        courses: [],
        profile_image: '',
      });

      
  
      const permissions = ref([]); // Lista de permissões disponíveis
  
      // Função para extrair permissões por curso ou papel
      const extractPermissionsByRole = (permissions) => {
        const permissionsByRole = {};
        permissions.forEach((role) => {
          const { course_name, permissions } = role;
          permissionsByRole[course_name] = permissions.map(permission => permission.type);
        });
        return permissionsByRole;
      };
  
      // Computed que usa a função extractPermissionsByRole
      const permissionsByRole = computed(() => {
        return extractPermissionsByRole(permissions.value);
      });
  
      const fetchStudentData = async () => {
        const id = route.params.id;
  
        try {
          const response = await studentStore.fetchStudentById(id); // Busca estudante
  
          // Atualiza campos do estudante
          student.id = response.student.id;
          student.name = response.student.name;
          student.email = response.student.email;
          student.enrollment_number = response.student.enrollment_number;
          student.courses = response.student.courses;
          student.profile_image = response.student.profile_image || ''; // Preenche a imagem de perfil, se disponível
  
          // Extrai permissões
          permissions.value = response.student.permissions || []; // Aqui, vamos considerar que a resposta traga permissões com cursos
        } catch (error) {
          console.error('Erro ao buscar dados do estudante:', error);
        }
      };
  
      const saveStudent = async () => {
        try {
          await studentStore.updateStudent(student.id, student); // Envia dados atualizados
          router.push('/dashboard/students'); // Redireciona após salvar
        } catch (error) {
          console.error('Erro ao salvar estudante:', error);
        }
      };
  
      onMounted(fetchStudentData);
  
      return {
        student,
        permissionsByRole,
        saveStudent,
      };
    },
  };
  </script>
  
  <style scoped>
  .v-container {
    max-width: 800px;
    margin: auto;
  }
  </style>
  