<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <h2 class="text-xl font-bold text-gray-800">我的權限快照</h2>
      <el-button :loading="loading" @click="load" :icon="Refresh" size="small">重新整理</el-button>
    </div>

    <el-alert
      v-if="error"
      :title="errorMessage"
      type="error"
      show-icon
      :closable="false"
      class="mb-4"
    />

    <el-skeleton v-if="loading && !snapshot" :rows="4" animated />

    <template v-if="snapshot">
      <p class="text-sm text-gray-500 mb-3">
        Sub：<span class="font-mono">{{ snapshot.user_sub }}</span>
      </p>

      <el-empty v-if="snapshot.roles.length === 0" description="目前沒有任何角色" />

      <el-table
        v-else
        :data="snapshot.roles"
        stripe
        border
        class="w-full shadow-sm"
      >
        <el-table-column prop="company_display_name" label="公司" min-width="150" />
        <el-table-column prop="site_display_name" label="站台" min-width="160" />
        <el-table-column prop="system_name" label="系統" min-width="150" />
        <el-table-column prop="role_name" label="角色" min-width="160" />
        <el-table-column prop="provider_role_name" label="Provider Role" min-width="180" />
      </el-table>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { usePermissionStore } from '@/stores/permission'

const permissionStore = usePermissionStore()

const snapshot = ref(null)
const loading = ref(false)
const error = ref(null)
const errorMessage = ref('')

async function load() {
  loading.value = true
  error.value = null
  try {
    await permissionStore.fetchMySnapshot()
    snapshot.value = permissionStore.snapshot
  } catch (err) {
    error.value = err
    const status = err.response?.status
    const detail = err.response?.data?.detail
    if (status === 401) {
      errorMessage.value = 'Token 已過期，請重新登入'
    } else if (detail) {
      errorMessage.value = `錯誤：${detail}`
    } else {
      errorMessage.value = '載入失敗，請稍後再試'
    }
  } finally {
    loading.value = false
  }
}

onMounted(load)
</script>
