import { http } from './index';
import type { EncryptedLoginParams, PublicKeyResponse } from '@/utils/encryption';

export interface LoginParams {
  account: string;
  password: string;
  role: string;
}

export interface LoginResponse {
  token: string;
  user: {
    id: number;
    name: string;
    role: 'admin' | 'school' | 'teacher';
    tenantId?: number;
    tenantName?: string;
    email?: string;
    phone?: string;
  };
}

export interface UserProfile {
  id: number;
  username?: string;
  name: string;
  role: 'admin' | 'school' | 'teacher' | 'parent';
  tenantId?: number;
  tenantName?: string;
  email?: string;
  phone?: string;
  avatar?: string;
  avatarUrl?: string;
}

// 登录
export function login(params: LoginParams): Promise<LoginResponse> {
  return http.post('/v1/auth/login', {
    username: params.account,
    password: params.password,
    role: params.role,
  });
}

// 登出
export function logout(): Promise<void> {
  return http.post('/v1/auth/logout');
}

// 刷新Token
export function refreshToken(): Promise<{ token: string }> {
  return http.post('/v1/auth/refresh');
}

// 获取当前用户信息
export function getProfile(): Promise<UserProfile> {
  return http.get('/v1/auth/profile');
}

// 修改个人信息
export interface UpdateProfileDto {
  name?: string;
  phone?: string;
  email?: string;
}

export interface UpdateProfileResponse {
  userInfo: UserProfile;
  token: string;
}

export function updateProfile(data: UpdateProfileDto): Promise<UpdateProfileResponse> {
  return http.put('/v1/auth/profile', data);
}

// 修改密码（修改成功后 token 失效，需重新登录）
export function changePassword(oldPassword: string, newPassword: string): Promise<void> {
  return http.post('/v1/auth/change-password', null, {
    params: { oldPassword, newPassword },
  });
}

// ========== RSA 加密登录相关 API ==========

/**
 * 获取 RSA 公钥
 */
export function getPublicKey(): Promise<PublicKeyResponse> {
  return http.get('/v1/auth/public-key');
}

/**
 * RSA 加密登录
 * @param params 加密后的登录参数
 */
export function loginEncrypted(params: EncryptedLoginParams): Promise<LoginResponse> {
  return http.post('/v1/auth/login/encrypted', {
    username: params.username,
    encryptedPassword: params.encryptedPassword,
    role: params.role,
    keyVersion: params.keyVersion,
  });
}
