/**
 * filekorolheader: 用户管理API接口 - 用户数据查询接口服务
 * 功能：API请求封装、数据转换、错误处理、分页查询
 * 路径：/central-config/tenant/user-management/components/userManagementApi
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SDK API调用，TypeScript类型安全
 */

import { getAuthToken } from "@/utils/token";
import {
  listSystemUsersApiV1UsersSystemUsersGet,
} from "@/lib/api/sdk.gen";

// API返回的用户数据类型
export interface UserData {
  id: string;
  tenant_id: string;
  email: string;
  username: string;
  full_name: string | null;
  phone: string | null;
  is_active?: boolean;
  status?: string;
  is_superuser: boolean;
  is_verified: boolean;
  created_at: string;
  updated_at: string;
  last_login_at: string | null;
  avatar_url: string | null;
  bio: string | null;
  display_name: string | null;
  department_id: string | null;
  department_name: string | null;
  scope: string;
  company_name: string | null;
}

// API响应接口
export interface UsersApiResponse {
  data: UserData[];
  total: number;
  page: number;
  size: number;
  total_pages: number;
  has_next: boolean;
  has_prev: boolean;
}

// 查询参数接口
export interface UsersQueryParams {
  search?: string;
  is_active?: boolean;
  page?: number;
  size?: number;
  order_by?: string;
  sort_order?: 'asc' | 'desc';
}

// 页面使用的用户数据类型（转换后的）
export interface User {
  id: string;
  username: string;
  email: string;
  fullName: string | null;
  phone: string | null;
  isActive: boolean;
  isSuperuser: boolean;
  isVerified: boolean;
  createdAt: string;
  updatedAt: string;
  lastLoginAt: string | null;
  avatarUrl: string | null;
  bio: string | null;
  displayName: string | null;
  departmentId: string | null;
  departmentName: string | null;
  scope: string;
  companyName: string | null;
  tenantId: string;
}

/**
 * 获取用户列表数据
 */
export async function fetchUsers(params: UsersQueryParams = {}): Promise<UsersApiResponse> {
  try {
    // 构建查询参数对象
    const queryParams: any = {};

    if (params.search) queryParams.search = params.search;
    if (params.is_active !== undefined) queryParams.is_active = params.is_active;
    if (params.page) queryParams.page = params.page;
    if (params.size) queryParams.size = params.size;
    if (params.order_by) queryParams.order_by = params.order_by;
    if (params.sort_order) queryParams.sort_order = params.sort_order;

    // 默认参数
    if (!params.page) queryParams.page = 1;
    if (!params.size) queryParams.size = 10;
    if (!params.sort_order) queryParams.sort_order = 'desc';

    // 使用SDK API调用用户查询接口，添加缓存破坏器和认证头部
    const token = getAuthToken();
    console.log('用户管理API调用参数:', queryParams);

    const response = await listSystemUsersApiV1UsersSystemUsersGet({
      query: {
        ...queryParams,
        // 添加时间戳防止缓存
        _t: Date.now(),
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`API error: ${response.error.message || 'Unknown error'}`);
    }

    const data = response.data as any;
    console.log('用户管理API响应:', data);

    // 转换响应数据格式以匹配现有的接口
    // API返回的数据结构: { data: [...], total: 25, page: 1, size: 10, ... }
    return {
      data: data?.data || [], // 注意：实际数据在 data.data 中
      total: data?.total || 0,
      page: data?.page || 1,
      size: data?.size || 10,
      total_pages: data?.total_pages || 0,
      has_next: data?.has_next || false,
      has_prev: data?.has_prev || false,
    };
  } catch (error) {
    console.error('Failed to fetch users:', error);
    throw error;
  }
}

/**
 * 将API数据转换为页面所需的用户数据格式
 * 优先显示display_name，其次full_name，最后username
 */
export function transformUserData(user: UserData): User {
  return {
    id: user.id,
    username: user.username,
    email: user.email,
    fullName: user.full_name,
    phone: user.phone,
    isActive: user.is_active !== undefined ? user.is_active : user.status === 'active',
    isSuperuser: user.is_superuser,
    isVerified: user.is_verified,
    createdAt: formatDate(user.created_at),
    updatedAt: formatDate(user.updated_at),
    lastLoginAt: user.last_login_at ? formatDate(user.last_login_at) : null,
    avatarUrl: user.avatar_url,
    bio: user.bio,
    displayName: user.display_name || user.full_name || user.username,
    departmentId: user.department_id,
    departmentName: user.department_name,
    scope: user.scope,
    companyName: user.company_name,
    tenantId: user.tenant_id,
  };
}

/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    }).replace(/\//g, '-');
  } catch (error) {
    return dateString;
  }
}

// Pagination state interface for page components
export interface PaginationState {
  page: number;
  size: number;
  total: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}