/**
 * 通知模板API服务
 * 
 * API接口列表：
 * - GET /api/v1/notification-template/page - 获取模板列表（分页）
 * - GET /api/v1/notification-template/{id} - 获取模板详情
 * - POST /api/v1/notification-template - 创建模板
 * - PUT /api/v1/notification-template/{id} - 更新模板
 * - DELETE /api/v1/notification-template/{id} - 删除模板
 * - POST /api/v1/notification-template/render - 渲染模板
 * - POST /api/v1/notification-template/preview - 预览模板
 * - POST /api/v1/notification-template/{id}/copy - 复制模板
 * - PUT /api/v1/notification-template/{id}/enable - 启用模板
 * - PUT /api/v1/notification-template/{id}/disable - 禁用模板
 * - GET /api/v1/notification-template/check-code - 检查编码唯一性
 */
import request from '../../../../utils/request';
import type { Page } from '../../../../types/base';
import type {
  NotificationTemplateDTO,
  NotificationTemplateQuery,
  TemplateRenderRequest,
} from './types';

const API_PREFIX = '/api/v1/notification-template';

/**
 * 获取模板列表（分页）
 */
export const getTemplateList = async (
  params: NotificationTemplateQuery
): Promise<Page<NotificationTemplateDTO>> => {
  return request.get(`${API_PREFIX}/page`, { params });
};

/**
 * 根据ID获取模板详情
 */
export const getTemplateById = async (id: number): Promise<NotificationTemplateDTO> => {
  return request.get(`${API_PREFIX}/${id}`);
};

/**
 * 创建模板
 */
export const createTemplate = async (
  template: Pick<NotificationTemplateDTO, 'name' | 'code' | 'description' | 'channelType' | 'titleTemplate' | 'contentTemplate' | 'templateConfig'>
): Promise<NotificationTemplateDTO> => {
  // 确保 channelType 在 templateConfig 之前
  const payload = {
    name: template.name,
    code: template.code,
    description: template.description,
    channelType: template.channelType,
    titleTemplate: template.titleTemplate,
    contentTemplate: template.contentTemplate,
    templateConfig: template.templateConfig,
    enabled: true, // 默认启用
  };
  return request.post(`${API_PREFIX}`, payload);
};

/**
 * 更新模板
 */
export const updateTemplate = async (
  id: number,
  template: Pick<NotificationTemplateDTO, 'id' | 'name' | 'code' | 'description' | 'channelType' | 'titleTemplate' | 'contentTemplate' | 'templateConfig' | 'enabled'>
): Promise<NotificationTemplateDTO> => {
  // 确保字段顺序：channelType 必须在 templateConfig 之前
  const payload = {
    id: template.id ?? id,
    name: template.name,
    code: template.code,
    description: template.description,
    channelType: template.channelType,
    titleTemplate: template.titleTemplate,
    contentTemplate: template.contentTemplate,
    enabled: template.enabled,
    templateConfig: template.templateConfig,
  };
  return request.put(`${API_PREFIX}/${id}`, payload);
};

/**
 * 删除模板
 */
export const deleteTemplate = async (id: number): Promise<void> => {
  return request.delete(`${API_PREFIX}/${id}`);
};

/**
 * 批量删除模板
 */
export const batchDeleteTemplates = async (ids: number[]): Promise<void> => {
  return request.delete(`${API_PREFIX}/batch`, { data: { ids } });
};

/**
 * 启用模板
 */
export const enableTemplate = async (id: number): Promise<void> => {
  return request.put(`${API_PREFIX}/${id}/enable`);
};

/**
 * 禁用模板
 */
export const disableTemplate = async (id: number): Promise<void> => {
  return request.put(`${API_PREFIX}/${id}/disable`);
};

/**
 * 批量启用模板
 */
export const batchEnableTemplates = async (ids: number[]): Promise<void> => {
  return request.put(`${API_PREFIX}/batch/enable`, { ids });
};

/**
 * 批量禁用模板
 */
export const batchDisableTemplates = async (ids: number[]): Promise<void> => {
  return request.put(`${API_PREFIX}/batch/disable`, { ids });
};

/**
 * 检查模板编码是否唯一
 * 注：后端暂无此接口，临时注释掉
 */
// export const checkTemplateCodeUnique = async (
//   code: string,
//   excludeId?: number
// ): Promise<boolean> => {
//   return request.get(`${API_PREFIX}/check-code`, {
//     params: { code, excludeId },
//   });
// };

/**
 * 渲染模板（根据模板内容）
 */
export const renderTemplate = async (
  templateContext: string,
  params: Record<string, any>
): Promise<string> => {
  return request.post(`${API_PREFIX}/render`, {
    templateContext,
    params
  });
};


/**
 * 发送测试消息
 */
export interface TestMessageRequest {
  channelId: number;
  notificationTemplateId: number;
  params: Record<string, any>;
}

export const sendTestMessage = async (testRequest: TestMessageRequest): Promise<void> => {
  return request.post('/api/v1/notification/send', testRequest);
};

// 模板变量可以在前端硬编码定义，不需要额外的API接口

/**
 * 复制模板
 */
export const copyTemplate = async (
  id: number,
  newName: string,
  newCode: string
): Promise<NotificationTemplateDTO> => {
  return request.post(`${API_PREFIX}/${id}/copy`, {
    name: newName,
    code: newCode,
  });
};

// renderTemplate 函数已在上面定义并自动导出
