/**
 * 认证工具函数
 * 统一使用 axios 实例，与其他 API 调用保持一致的错误处理
 */
import api from "@/shared/api/axios";
import { User } from "@/shared/types/user";

// Re-export User 类型以保持向后兼容
export type { User };

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

interface ApiResponse<T> {
    success: boolean;
    message: string;
    data: T;
    code: number;
}

/**
 * 用户注册
 */
export async function register(phone: string, password: string, username?: string): Promise<AuthResponse> {
    try {
        const { data: payload } = await api.post<ApiResponse<null>>('/api/auth/register', {
            phone, password, username
        });
        return { success: payload.success, message: payload.message };
    } catch (err: any) {
        return {
            success: false,
            message: err.response?.data?.message || '注册失败',
        };
    }
}

/**
 * 用户登录
 */
export async function login(phone: string, password: string): Promise<AuthResponse> {
    try {
        const { data: payload } = await api.post<ApiResponse<{ user?: User }>>('/api/auth/login', {
            phone, password
        });
        return { success: payload.success, message: payload.message, user: payload.data?.user };
    } catch (err: any) {
        if (err.response?.status === 403 && err.response?.data?.data?.reason === 'PAYMENT_REQUIRED') {
            return {
                success: false,
                message: err.response.data.message,
                paymentToken: err.response.data.data.payment_token,
            };
        }
        return {
            success: false,
            message: err.response?.data?.message || '登录失败',
        };
    }
}

/**
 * 用户登出
 */
export async function logout(): Promise<AuthResponse> {
    const { data: payload } = await api.post<ApiResponse<null>>('/api/auth/logout');
    return { success: payload.success, message: payload.message };
}

/**
 * 修改密码
 */
export async function changePassword(oldPassword: string, newPassword: string): Promise<AuthResponse> {
    const { data: payload } = await api.post<ApiResponse<null>>('/api/auth/change-password', {
        old_password: oldPassword, new_password: newPassword
    });
    return { success: payload.success, message: payload.message };
}

/**
 * 获取当前用户
 */
export async function getCurrentUser(): Promise<User | null> {
    try {
        const { data: payload } = await api.get<ApiResponse<User>>('/api/auth/me');
        return payload.data || null;
    } 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';
}
