/**
 * 用户管理 API
 */

import { get, post, put, del } from '../request'
import type { PageParams } from '../config'

// 用户状态枚举
export type UserStatus = 'active' | 'inactive' | 'pending'

// 用户接口
export interface User {
  id: number
  username: string
  realName: string
  email: string
  phone: string
  position: string
  department: string
  role: string
  status: UserStatus
  lastLoginTime: string
  createTime: string
  avatar?: string
}

// 用户表单接口
export interface UserForm {
  username: string
  realName: string
  email: string
  phone: string
  position: string
  department: string
  role: string
  status: UserStatus
}

// 批量操作接口
export interface BatchOperation {
  ids: number[]
  action: 'delete' | 'activate' | 'deactivate' | 'change_role' | 'assign_position' | 'assign_team'
  value?: string | number  // 角色值、岗位ID、团队ID等
}

// 密码重置响应接口
export interface PasswordResetResponse {
  tempPassword: string
  expiresAt: string
}

// 获取用户列表
export const getUserList = (params?: PageParams & { 
  keyword?: string
  status?: UserStatus
  role?: string 
}) => {
  const q: any = { ...params }
  if ('pageSize' in q) {
    q.page_size = q.pageSize
    delete q.pageSize
  }
  // 清理空参数，避免传递空字符串导致后端校验报错
  if (!q.keyword) delete q.keyword
  if (!q.role) delete q.role
  // 映射前端 status -> 后端 is_active（仅支持 active/disabled）
  if (q.status === 'active') {
    q.is_active = true
  } else if (q.status === 'disabled') {
    q.is_active = false
  }
  delete q.status
  // 列表路由为 "/" 结尾，追加斜杠可避免 307
  return get('/api/v1/users/', q)
}

// 获取用户详情
export const getUserDetail = (id: number) => {
  return get(`/api/v1/users/${id}`)
}

// 创建用户
export const createUser = (data: UserForm) => {
  return post('/api/v1/users', data)
}

// 更新用户
export const updateUser = (id: number | string, data: UserForm) => {
  return put(`/api/v1/users/${id}`, data)
}

// 团队相关操作改为调用 /api/v1/users 路由
export const addUserToTeamAdmin = (userId: number, teamId: number, role: 'member'|'leader' = 'member') => {
  return post(`/api/v1/users/${userId}/teams/${teamId}?role=${role}`)
}

export const removeUserFromTeamAdmin = (userId: number, teamId: number) => {
  return del(`/api/v1/users/${userId}/teams/${teamId}`)
}

// 删除用户
export const deleteUser = (id: number) => {
  return del(`/api/v1/users/${id}`)
}

// 重置密码
export const resetUserPassword = (id: number) => {
  return post(`/api/v1/admin/users/${id}/reset-password`)
}

// 批量操作
export const batchOperation = (data: BatchOperation) => {
  return post('/api/v1/admin/users/batch', data)
}

// 获取用户统计
export const getUserStatistics = () => {
  return get('/api/v1/admin/dashboard/stats')
}

// 与钉钉同步员工
export const syncWithDingTalk = () => {
  return post('/api/v1/employee-sync/incremental-sync')
}
