import { readingApi } from "./client";
import type {
  LoginResponse as ApiLoginResponse,
  ResultLoginResponse,
  ResultUserInfoResponse,
  UserInfoResponse,
} from "./generated/model";

// 兼容现有登录页字段命名（account）
export interface LoginParams {
  account: string;
  password: string;
  role: string;
}

// Java 后端返回的平铺结构（保持与现有业务使用一致）
export interface LoginResponse extends Required<
  Omit<ApiLoginResponse, "tenantId" | "role">
> {
  role: "admin" | "school" | "teacher" | "parent";
  tenantId?: number;
}

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

// 登录
export function login(params: LoginParams): Promise<LoginResponse> {
  return readingApi
    .login({
      username: params.account,
      password: params.password,
      role: params.role,
    })
    .then((res) => {
    const wrapped = res as ResultLoginResponse;
    const data = (wrapped.data ?? {}) as ApiLoginResponse;

    return {
      token: data.token ?? "",
      userId: data.userId ?? 0,
      username: data.username ?? "",
      name: data.name ?? "",
      role: (data.role as LoginResponse["role"]) ?? "teacher",
      tenantId: data.tenantId,
    };
    });
}

// 登出
export function logout(): Promise<void> {
  return readingApi.logout().then(() => undefined);
}

// 刷新Token
export function refreshToken(): Promise<{ token: string }> {
  // OpenAPI 目前未定义 refresh 接口，暂时保留原有调用路径以兼容后端
  const { http } = require("./index");
  return http.post("/api/v1/auth/refresh");
}

// 获取当前用户信息
export function getProfile(): Promise<UserProfile> {
  return readingApi.getCurrentUser().then((res) => {
    const wrapped = res as ResultUserInfoResponse;
    const data = (wrapped.data ?? {}) as UserInfoResponse;

    return {
      id: data.id ?? 0,
      name: data.name ?? "",
      role: (data.role as UserProfile["role"]) ?? "teacher",
      tenantId: data.tenantId,
      tenantName: undefined,
      email: data.email,
      phone: data.phone,
      avatar: data.avatarUrl,
    };
  });
}
