import request from "@/utils/request";
import type { PaginationParams, PaginationResponse } from "@/types/api";
import type { Menu } from "./menus";

export interface Tenant {
  id: number;
  name: string;
  code: string;
  domain?: string;
  description?: string;
  isSuper: number;
  tenantType?: string;
  validState: number;
  createBy?: number;
  updateBy?: number;
  createTime?: string;
  updateTime?: string;
  menus?: Array<{
    id: number;
    menu: Menu;
  }>;
  _count?: {
    users: number;
    roles: number;
  };
}

export interface CreateTenantForm {
  name: string;
  code: string;
  domain?: string;
  description?: string;
  menuIds?: number[];
}

export interface UpdateTenantForm {
  name?: string;
  code?: string;
  domain?: string;
  description?: string;
  validState?: number;
  menuIds?: number[];
}

// 获取租户列表
export async function getTenantsList(
  params: PaginationParams
): Promise<PaginationResponse<Tenant>> {
  const response = await request.get<any, PaginationResponse<Tenant>>(
    "/api/tenants",
    {
      params,
    }
  );
  return response;
}

// 获取单个租户详情
export async function getTenantDetail(id: number): Promise<Tenant> {
  const response = await request.get<any, Tenant>(`/api/tenants/${id}`);
  return response;
}

// 创建租户
export async function createTenant(data: CreateTenantForm): Promise<Tenant> {
  const response = await request.post<any, Tenant>("/api/tenants", data);
  return response;
}

// 更新租户
export async function updateTenant(
  id: number,
  data: UpdateTenantForm
): Promise<Tenant> {
  const response = await request.put<any, Tenant>(`/api/tenants/${id}`, data);
  return response;
}

// 删除租户
export async function deleteTenant(id: number): Promise<void> {
  return await request.delete<any, void>(`/api/tenants/${id}`);
}

// 获取租户的菜单树
export async function getTenantMenus(id: number): Promise<Menu[]> {
  const response = await request.get<any, Menu[]>(`/api/tenants/${id}/menus`);
  return response;
}

// 兼容性导出：保留 tenantsApi 对象
export const tenantsApi = {
  getList: getTenantsList,
  getDetail: getTenantDetail,
  create: createTenant,
  update: updateTenant,
  delete: deleteTenant,
  getTenantMenus: getTenantMenus,
};
