import { Todo, CreateTodoInput } from '../../data/models/Todo';
import { ApiClient } from '@shared/api';

export class TodoService {
  private apiClient: ApiClient;
  private mockMode: boolean;
  private todos: Todo[] = [];

  constructor(apiUrl: string = 'http://localhost:8080', mockMode: boolean = false) {
    this.apiClient = new ApiClient({ baseUrl: apiUrl });
    this.mockMode = mockMode;
  }

  async getTodos(): Promise<Todo[]> {
    if (this.mockMode) {
      return [...this.todos];
    }
    return this.apiClient.get<Todo[]>('/api/todos');
  }

  async createTodo(input: CreateTodoInput): Promise<Todo> {
    if (this.mockMode) {
      const newTodo: Todo = {
        id: Date.now().toString(),
        title: input.title,
        completed: false,
        createdAt: new Date(),
        updatedAt: new Date(),
      };
      this.todos.push(newTodo);
      return newTodo;
    }
    return this.apiClient.post<Todo>('/api/todos', input);
  }

  async toggleTodo(id: string): Promise<Todo | null> {
    if (this.mockMode) {
      const todo = this.todos.find(t => t.id === id);
      if (!todo) return null;

      todo.completed = !todo.completed;
      todo.updatedAt = new Date();
      return todo;
    }

    const todo = await this.apiClient.get<Todo>(`/api/todos/${id}`);
    return this.apiClient.put<Todo>(`/api/todos/${id}`, {
      completed: !todo.completed
    });
  }

  async deleteTodo(id: string): Promise<boolean> {
    if (this.mockMode) {
      const index = this.todos.findIndex(t => t.id === id);
      if (index === -1) return false;

      this.todos.splice(index, 1);
      return true;
    }

    try {
      await this.apiClient.delete(`/api/todos/${id}`);
      return true;
    } catch (error) {
      return false;
    }
  }
}