/**
 * 认证工具函数
 */

const API_BASE = typeof window === 'undefined'
    ? (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8006')
    : '';

export interface User {
    id: string;
    phone: string;
    username: string | null;
    role: string;
    is_active: boolean;
    expires_at: string | null;
}

export interface AuthResponse {
    success: boolean;
    message: string;
    user?: User;
}

/**
 * 用户注册
 */
export async function register(phone: string, password: string, username?: string): Promise<AuthResponse> {
    const res = await fetch(`${API_BASE}/api/auth/register`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ phone, password, username })
    });
    return res.json();
}

/**
 * 用户登录
 */
export async function login(phone: string, password: string): Promise<AuthResponse> {
    const res = await fetch(`${API_BASE}/api/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ phone, password })
    });
    return res.json();
}

/**
 * 用户登出
 */
export async function logout(): Promise<AuthResponse> {
    const res = await fetch(`${API_BASE}/api/auth/logout`, {
        method: 'POST',
        credentials: 'include'
    });
    return res.json();
}

/**
 * 修改密码
 */
export async function changePassword(oldPassword: string, newPassword: string): Promise<AuthResponse> {
    const res = await fetch(`${API_BASE}/api/auth/change-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
    });
    return res.json();
}

/**
 * 获取当前用户
 */
export async function getCurrentUser(): Promise<User | null> {
    try {
        const res = await fetch(`${API_BASE}/api/auth/me`, {
            credentials: 'include'
        });
        if (!res.ok) return null;
        return res.json();
    } catch {
        return null;
    }
}

/**
 * 检查是否已登录
 */
export async function isAuthenticated(): Promise<boolean> {
    const user = await getCurrentUser();
    return user !== null;
}

/**
 * 检查是否是管理员
 */
export async function isAdmin(): Promise<boolean> {
    const user = await getCurrentUser();
    return user?.role === 'admin';
}
