import { request } from '../../utils/axios';

// 邮件模板 VO 类型
export interface MailTemplateVO {
  id?: number;
  name: string;
  code: string;
  accountId?: number;
  nickname?: string;
  title?: string;
  content?: string;
  params?: string;
  status?: number;
  remark?: string;
}

// 邮件发送请求 VO 类型
export interface MailSendReqVO {
  mail: string;
  templateCode: string;
  templateParams: Record<string, any>;
}

// 分页参数类型
export interface PageParam {
  pageNo?: number;
  pageSize?: number;
  name?: string;
  code?: string;
  status?: number;
  [key: string]: any;
}

// 分页响应类型
export interface PageResponse<T> {
  list: T[];
  total: number;
  records?: T[]; // 兼容其他响应格式
  data?: {
    list: T[];
    total: number;
  };
}

// 邮件模板 API
export const emailTemplateApi = {
  // 查询邮件模版列表
  getMailTemplatePage: async (params: PageParam): Promise<PageResponse<MailTemplateVO>> => {
    const response: any = await request.get({
      url: '/system/mail-template/page',
      params,
    });
    
    // 处理响应数据格式
    if (response && typeof response === 'object') {
      if ('data' in response && response.data) {
        return response.data;
      } else if ('list' in response || 'records' in response) {
        return {
          list: response.list || response.records || [],
          total: response.total || 0,
        };
      }
    }
    return { list: [], total: 0 };
  },

  // 查询邮件模版详情（兼容 { code, data } 与直接返回 data 两种格式）
  getMailTemplate: async (id: number): Promise<MailTemplateVO> => {
    const response: any = await request.get({
      url: '/system/mail-template/get',
      params: { id },
    });
    const raw = response?.data ?? response;
    return raw?.data ?? raw;
  },

  // 新增邮件模版（不返回响应体，避免被误当作成功提示展示）
  createMailTemplate: async (data: MailTemplateVO): Promise<void> => {
    await request.post({
      url: '/system/mail-template/create',
      data,
    });
    return;
  },

  // 修改邮件模版
  updateMailTemplate: async (data: MailTemplateVO): Promise<void> => {
    await request.put({
      url: '/system/mail-template/update',
      data,
    });
  },

  // 删除邮件模版
  deleteMailTemplate: async (id: number): Promise<void> => {
    await request.delete({
      url: '/system/mail-template/delete',
      params: { id },
    });
  },

  // 发送邮件
  sendMail: async (data: MailSendReqVO): Promise<string | number | null> => {
    const response: any = await request.post({
      url: '/system/mail-template/send-mail',
      data,
    });
    return response?.data || response || null;
  },
};

// 为了兼容旧代码，导出别名
export const listEmailTemplates = emailTemplateApi.getMailTemplatePage;
export const getEmailTemplatesInfo = emailTemplateApi.getMailTemplate;
export const addEmailTemplates = emailTemplateApi.createMailTemplate;
export const updateEmailTemplates = emailTemplateApi.updateMailTemplate;
export const delEmailTemplates = emailTemplateApi.deleteMailTemplate;

