import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Ticket, TicketReply, TicketSubmitForm, TicketQueryParams, TicketStats } from './model';

const BASE = '/app/ticket';

/** 查询我的工单（分页） */
export async function myTickets(params: TicketQueryParams) {
  const res = await request.get<ApiResult<PageResult<Ticket>>>(BASE + '/my', { params });
  if (res.code === 0) return res.data;
  return Promise.reject(new Error(res.message));
}

/** 提交工单 */
export async function submitTicket(data: TicketSubmitForm) {
  const res = await request.post<ApiResult<Ticket>>(BASE + '/submit', data);
  if (res.code === 0) return res.data;
  return Promise.reject(new Error(res.message));
}

/** 获取工单详情 */
export async function getTicket(ticketId: number) {
  const res = await request.get<ApiResult<Ticket>>(BASE + '/' + ticketId);
  if (res.code === 0 && res.data) return res.data;
  return Promise.reject(new Error(res.message));
}

/** 关闭工单 */
export async function closeTicket(ticketId: number) {
  const res = await request.put<ApiResult<unknown>>(BASE + `/${ticketId}/close`);
  if (res.code === 0) return res.message;
  return Promise.reject(new Error(res.message));
}

/** 获取工单回复列表 */
export async function getTicketReplies(ticketId: number) {
  const res = await request.get<ApiResult<TicketReply[]>>(BASE + `/${ticketId}/replies`);
  if (res.code === 0 && res.data) return res.data;
  return Promise.reject(new Error(res.message));
}

/** 提交工单回复 */
export async function replyTicket(data: { ticketId: number; content: string }) {
  const res = await request.post<ApiResult<TicketReply>>(BASE + '/reply', data);
  if (res.code === 0) return res.data;
  return Promise.reject(new Error(res.message));
}

/** 获取工单统计 */
export async function getTicketStats() {
  const res = await request.get<ApiResult<TicketStats>>(BASE + '/stats');
  if (res.code === 0 && res.data) return res.data;
  return Promise.reject(new Error(res.message));
}
