import request from '@/utils/request';
import type {
    ServerCategoryResponse,
    ServerCategoryQuery,
    ServerCategoryRequest,
    ServerResponse,
    ServerRequest,
    ServerConnectionTestResult,
    ServerHardwareCollectionResult,
    AlertRuleResponse,
    AlertRuleQuery,
    AlertRuleRequest,
    ServerMonitorResponse,
    TimeRange,
    MetricType,
} from './types';
import type { ServerFormValues } from './schema';
import type { Page } from '@/types/base';

// API 基础路径
const CATEGORY_URL = '/api/v1/server-category';
const SERVER_URL = '/api/v1/server';
const ALERT_RULE_URL = '/api/v1/server/alert-rule';
const MONITOR_URL = '/api/v1/server/monitor';

// ==================== 服务器分类 ====================

/**
 * 获取服务器分类列表
 */
export const getServerCategories = (params?: ServerCategoryQuery) =>
    request.get<ServerCategoryResponse[]>(`${CATEGORY_URL}/list`, { params });

/**
 * 获取服务器分类分页列表
 */
export const getServerCategoryPage = (params?: ServerCategoryQuery) =>
    request.get<Page<ServerCategoryResponse>>(`${CATEGORY_URL}/page`, { params });

/**
 * 获取服务器分类详情
 */
export const getServerCategory = (id: number) =>
    request.get<ServerCategoryResponse>(`${CATEGORY_URL}/${id}`);

/**
 * 创建服务器分类
 */
export const createServerCategory = (data: ServerCategoryRequest) =>
    request.post<ServerCategoryResponse>(CATEGORY_URL, data);

/**
 * 更新服务器分类
 */
export const updateServerCategory = (id: number, data: ServerCategoryRequest) =>
    request.put<ServerCategoryResponse>(`${CATEGORY_URL}/${id}`, data);

/**
 * 删除服务器分类
 */
export const deleteServerCategory = (id: number) =>
    request.delete<void>(`${CATEGORY_URL}/${id}`);

/**
 * 批量删除服务器分类
 */
export const batchDeleteServerCategories = (ids: number[]) =>
    request.post<void>(`${CATEGORY_URL}/batch-delete`, { ids });

// ==================== 服务器 ====================

/**
 * 获取服务器列表（不分页）
 */
export const getServerList = (params?: {
    categoryId?: number;
    status?: string;
    osType?: string;
}) =>
    request.get<ServerResponse[]>(`${SERVER_URL}/list`, { params });

/**
 * 获取服务器分页列表
 */
export const getServers = (params?: {
    categoryId?: number;
    status?: string;
    osType?: string;
    pageNum?: number;
    pageSize?: number;
}) =>
    request.get<Page<ServerResponse>>(`${SERVER_URL}/page`, { params });

/**
 * 获取服务器详情
 */
export const getServer = (id: number) =>
    request.get<ServerResponse>(`${SERVER_URL}/${id}`);

/**
 * 创建服务器
 */
export const createServer = (data: ServerFormValues) =>
    request.post<ServerResponse>(SERVER_URL, data);

/**
 * 更新服务器
 */
export const updateServer = (id: number, data: ServerFormValues) =>
    request.put<ServerResponse>(`${SERVER_URL}/${id}`, data);

/**
 * 删除服务器
 */
export const deleteServer = (id: number) =>
    request.delete<void>(`${SERVER_URL}/${id}`);

/**
 * 批量删除服务器
 */
export const batchDeleteServers = (ids: number[]) =>
    request.post<void>(`${SERVER_URL}/batch-delete`, { ids });

/**
 * 测试服务器连接（轻量级）
 * 仅验证连接是否成功，不采集硬件信息
 */
export const testServerConnection = (id: number) =>
    request.post<ServerConnectionTestResult>(`${SERVER_URL}/${id}/test-connection`);

/**
 * 采集服务器硬件信息
 * 采集并更新服务器硬件信息（hostname、CPU、内存、磁盘等）
 */
export const collectServerHardware = (id: number) =>
    request.post<ServerHardwareCollectionResult>(`${SERVER_URL}/${id}/collect-hardware`);

// ==================== 告警规则 ====================

/**
 * 获取告警规则列表
 */
export const getAlertRules = (params?: AlertRuleQuery) =>
    request.get<AlertRuleResponse[]>(`${ALERT_RULE_URL}/list`, { params });

/**
 * 获取告警规则分页列表
 */
export const getAlertRulePage = (params?: AlertRuleQuery) =>
    request.get<Page<AlertRuleResponse>>(`${ALERT_RULE_URL}/page`, { params });

/**
 * 获取告警规则详情
 */
export const getAlertRule = (id: number) =>
    request.get<AlertRuleResponse>(`${ALERT_RULE_URL}/${id}`);

/**
 * 创建告警规则
 */
export const createAlertRule = (data: AlertRuleRequest) =>
    request.post<AlertRuleResponse>(ALERT_RULE_URL, data);

/**
 * 更新告警规则
 */
export const updateAlertRule = (id: number, data: AlertRuleRequest) =>
    request.put<AlertRuleResponse>(`${ALERT_RULE_URL}/${id}`, data);

/**
 * 删除告警规则
 */
export const deleteAlertRule = (id: number) =>
    request.delete<void>(`${ALERT_RULE_URL}/${id}`);

// ==================== 服务器监控 ====================

/**
 * 获取服务器监控数据
 * @param serverId 服务器ID
 * @param timeRange 时间范围
 * @param metrics 指标类型列表（可选，为空则查询所有）
 */
export const getServerMonitorMetrics = (
    serverId: number,
    timeRange: TimeRange,
    metrics?: MetricType[]
) =>
    request.get<ServerMonitorResponse>(`${MONITOR_URL}/${serverId}/metrics`, {
        params: {
            timeRange,
            metrics: metrics?.join(','),
        },
    });
