import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import { api, setAccessToken, clearAccessToken } from '../api/client'
import { router } from '../router'

interface UserProfile {
  id: string; email: string; display_name: string
  title?: string; avatar_url?: string; platform_role?: string; phone?: string
}
interface TenantInfo {
  id: string; name: string; slug: string; plan_type?: string; role: string
}

export const useAuthStore = defineStore('auth', () => {
  // accessToken 仅存内存（不写入 localStorage/sessionStorage）
  const accessToken = ref('')
  // 用户信息仅存内存（刷新后从 /auth/me 重新拉取）
  const user = ref<UserProfile | null>(null)
  const tenants = ref<TenantInfo[]>([])
  const currentTenant = ref<TenantInfo | null>(null)
  const initialized = ref(false)

  const isAuthenticated = computed(() => !!accessToken.value && !!user.value)
  const currentRole = computed(() => currentTenant.value?.role || 'viewer')

  /** 页面初始化时从 HttpOnly refresh_token cookie 恢复会话 */
  async function initialize() {
    if (initialized.value) return
    initialized.value = true

    try {
      // 使用原始 axios 绕过 response 拦截器，不把 401 当错误处理
      const res = await axios.post('/api/v1/auth/refresh', null, {
        validateStatus: (s) => s === 200,
      })
      if (!res.data.access_token) {
        // 无有效 refresh token（已登出或过期），直接返回未登录态
        clearAccessToken()
        accessToken.value = ''
        return
      }
      accessToken.value = res.data.access_token
      setAccessToken(res.data.access_token)

      // 拿到 access_token 后再用 api 实例（带拦截器）
      const meRes = await api.get('/auth/me')
      user.value = meRes.data

      const tenantsRes = await api.get('/auth/tenants')
      const td = tenantsRes.data
      tenants.value = td.tenants || []
      currentTenant.value = (td.tenants || []).find((t: any) => t.id === td.current_tenant_id) || (td.tenants || [])[0] || null
    } catch {
      clearAccessToken()
      accessToken.value = ''
    }
  }

  async function login(email: string, password: string) {
    const res = await api.post('/auth/login', { email, password })
    setAuth(res.data)
    return res.data
  }

  async function register(data: { email: string; password: string; display_name: string; hospital_name?: string; department_name?: string; verify_token?: string }) {
    const res = await api.post('/auth/register', data)
    setAuth(res.data)
    return res.data
  }

  function setAuth(data: any) {
    accessToken.value = data.token.access_token
    setAccessToken(data.token.access_token)
    user.value = data.user
    tenants.value = data.tenants
    currentTenant.value = data.tenants?.[0] || null
  }

  async function logout() {
    // 通知后端吊销 refresh token + 清除 cookie
    try {
      await api.post('/auth/logout')
    } catch {
      // 即使后端调用失败，也要清除本地状态（比如后端已重启，token 已过期等）
    }
    accessToken.value = ''
    clearAccessToken()
    user.value = null
    tenants.value = []
    currentTenant.value = null
    sessionStorage.removeItem('pending_invite')
    router.push('/')
  }

  return { accessToken, user, tenants, currentTenant, isAuthenticated, currentRole, initialized, initialize, login, register, logout }
})
