import { apiClient } from './api';
import type {
  Todo,
  CreateTodoRequest,
  UpdateTodoRequest,
} from '@/types';

class TodoServiceClass {
  async create(data: CreateTodoRequest): Promise<Todo> {
    try {
      const response = await apiClient.post<{ success: boolean; data: Todo }>('/todos', data);
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      throw new Error('创建失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '创建待办失败');
    }
  }

  async getUserTodos(params?: { status?: string; page?: number; limit?: number }): Promise<Todo[]> {
    const queryParams = new URLSearchParams();
    if (params?.status) queryParams.append('status', params.status);
    if (params?.page) queryParams.append('page', params.page.toString());
    if (params?.limit) queryParams.append('limit', params.limit.toString());

    const url = `/todos${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
    const response = await apiClient.get<{ success: boolean; data: Todo[] }>(url);
    return response.data.data || [];
  }

  async getPendingTodos(): Promise<Todo[]> {
    const response = await apiClient.get<{ success: boolean; data: Todo[] }>('/todos/pending');
    return response.data.data || [];
  }

  async getCompletedTodos(): Promise<Todo[]> {
    const response = await apiClient.get<{ success: boolean; data: Todo[] }>('/todos/completed');
    return response.data.data || [];
  }

  async getConfirmedTodos(): Promise<Todo[]> {
    const response = await apiClient.get<{ success: boolean; data: Todo[] }>('/todos/confirmed');
    return response.data.data || [];
  }

  async getById(id: string): Promise<Todo> {
    try {
      const response = await apiClient.get<{ success: boolean; data: Todo }>(`/todos/${id}`);
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      throw new Error('获取失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '待办不存在');
    }
  }

  async update(id: string, data: UpdateTodoRequest): Promise<Todo> {
    try {
      const response = await apiClient.put<{ success: boolean; data: Todo }>(`/todos/${id}`, data);
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      throw new Error('更新失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '更新待办失败');
    }
  }

  async delete(id: string): Promise<void> {
    try {
      await apiClient.delete(`/todos/${id}`);
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '删除失败');
    }
  }
}

export const TodoService = new TodoServiceClass();
