import { UserManager, WebStorageStateStore, type User } from 'oidc-client-ts'
import { ref, readonly } from 'vue'

// Authentik OIDC 配置 - note 应用
const oidcConfig = {
    authority: 'https://auth.yuany3721.site/application/o/note/',
    client_id: 'xzqQVQHINluS4pW0qhZAEg1YAYsS2j8HMJnVcUT5',
    redirect_uri: window.location.origin + '/auth/callback',
    response_type: 'code',
    scope: 'openid profile email',
    userStore: new WebStorageStateStore({
        store: window.localStorage,
        prefix: 'oidc.note.',
    }),
    metadata: {
        issuer: 'https://auth.yuany3721.site/application/o/note/',
        authorization_endpoint: 'https://auth.yuany3721.site/application/o/authorize/',
        token_endpoint: 'https://auth.yuany3721.site/application/o/token/',
        userinfo_endpoint: 'https://auth.yuany3721.site/application/o/userinfo/',
        end_session_endpoint: 'https://auth.yuany3721.site/application/o/note/end-session/',
        jwks_uri: 'https://auth.yuany3721.site/application/o/note/jwks/',
    },
}

// 创建 UserManager 实例
const userManager = new UserManager(oidcConfig)

// 响应式状态
const user = ref<User | null>(null)
const isAuthenticated = ref(false)
const isLoading = ref(true)

// 初始化用户状态
export async function initAuth(): Promise<void> {
    try {
        const currentUser = await userManager.getUser()
        user.value = currentUser
        isAuthenticated.value = currentUser !== null && !currentUser.expired
    } catch (error) {
        console.error('[Auth] Init failed:', error)
        isAuthenticated.value = false
    } finally {
        isLoading.value = false
    }
}

// 登录跳转
export async function login(): Promise<void> {
    await userManager.signinRedirect()
}

// 处理登录回调
export async function handleCallback(): Promise<void> {
    try {
        const currentUser = await userManager.signinRedirectCallback()
        user.value = currentUser
        isAuthenticated.value = currentUser !== null && !currentUser.expired
    } catch (error) {
        console.error('[Auth] Callback failed:', error)
        throw error
    }
}

// 登出
export async function logout(): Promise<void> {
    await userManager.signoutRedirect()
}

// 获取 access token
export function getAccessToken(): string | undefined {
    return user.value?.access_token
}

// 获取用户信息
export function getUserInfo() {
    return user.value?.profile
}

// 获取用户 name（用于后端 API）
export function getUserName(): string {
    return user.value?.profile?.preferred_username || 
           user.value?.profile?.name || 
           user.value?.profile?.email || 
           'default'
}

// 导出 readonly 状态
export const authState = {
    user: readonly(user),
    isAuthenticated: readonly(isAuthenticated),
    isLoading: readonly(isLoading),
}

// 导出 userManager 用于高级操作
export { userManager }
