/**
 * 租户管理员 CRUD API 调用。
 *
 * 复用 apiClient（已含 JWT 拦截器 + 响应解包）。
 * 端点前缀：/admin/tenant-admins
 */

import { apiClient } from "./client";

/* ------------------------------------------------------------------ */
/*  类型定义                                                           */
/* ------------------------------------------------------------------ */

/** 列表项（后端 CamelModel 序列化为 camelCase） */
export interface TenantAdminItem {
  id: number;
  username: string;
  displayName: string | null;
  tenantId: number;
  tenantName: string | null;
  adminType: string;
  managedSiteIds: number[];
  isActive: boolean;
  createdAt: string;
  lastLoginAt: string | null;
}

/** 分页响应 */
export interface TenantAdminListResponse {
  items: TenantAdminItem[];
  total: number;
  page: number;
  page_size: number;
}

/** 创建请求 */
export interface TenantAdminCreatePayload {
  username: string;
  password: string;
  displayName: string;
  tenantId: number;
  managedSiteIds: number[];
}

/** 编辑请求（所有字段可选） */
export interface TenantAdminEditPayload {
  username?: string;
  displayName?: string;
  managedSiteIds?: number[];
  isActive?: boolean;
}

/** 重置密码请求 */
export interface ResetPasswordPayload {
  newPassword: string;
}

/* ------------------------------------------------------------------ */
/*  API 调用                                                           */
/* ------------------------------------------------------------------ */

/** 列表查询（分页 + 关键词搜索 + 可选包含已禁用） */
export async function fetchTenantAdmins(params: {
  page?: number;
  page_size?: number;
  keyword?: string;
  include_inactive?: boolean;
}): Promise<TenantAdminListResponse> {
  const { data } = await apiClient.get<TenantAdminListResponse>(
    "/admin/tenant-admins",
    { params },
  );
  return data;
}

/** 创建租户管理员 */
export async function createTenantAdmin(
  payload: TenantAdminCreatePayload,
): Promise<TenantAdminItem> {
  const { data } = await apiClient.post<TenantAdminItem>(
    "/admin/tenant-admins",
    payload,
  );
  return data;
}

/** 编辑租户管理员 */
export async function editTenantAdmin(
  id: number,
  payload: TenantAdminEditPayload,
): Promise<TenantAdminItem> {
  const { data } = await apiClient.patch<TenantAdminItem>(
    `/admin/tenant-admins/${id}`,
    payload,
  );
  return data;
}

/** 重置密码 */
export async function resetTenantAdminPassword(
  id: number,
  payload: ResetPasswordPayload,
): Promise<void> {
  await apiClient.post(`/admin/tenant-admins/${id}/reset-password`, payload);
}

/** 删除租户管理员（软删除） */
export async function deleteTenantAdmin(id: number): Promise<void> {
  await apiClient.delete(`/admin/tenant-admins/${id}`);
}
