/**
 * Task Service
 * Handles task-related API calls
 */

import { apiClient } from '../client'
import type { Author } from '../types'

export enum Routine {
  NONE = 0,
  DAILY = 1,
  WEEKLY = 2,
  MONTHLY = 3,
  YEARLY = 4
}

export interface Task {
  id: string
  title: string
  description: string
  deadline: number // Unix timestamp
  routine: Routine
  tags: string[]
  author: Author
}

export interface CreateTaskRequest {
  title: string
  description?: string
  deadline?: number
  routine?: Routine
  tags?: string[]
  author?: Author
}

export interface CreateTaskResponse {
  task: Task
}

export interface GetTaskResponse {
  task: Task
}

export interface ListTasksResponse {
  tasks: Task[]
}

export interface UpdateTaskRequest {
  id: string
  title?: string
  description?: string
  deadline?: number
  routine?: Routine
  tags?: string[]
  author?: Author
}

export interface UpdateTaskResponse {
  task: Task
}

export interface DeleteTaskResponse {
  success: boolean
}

export const taskService = {
  /**
   * Create a new task
   */
  async createTask(data: CreateTaskRequest): Promise<Task> {
    const response = await apiClient.post<CreateTaskResponse>('/tasks', data)
    return response.task
  },

  /**
   * Get a task by ID
   */
  async getTask(id: string): Promise<Task> {
    const response = await apiClient.get<GetTaskResponse>(`/tasks/${id}`)
    return response.task
  },

  /**
   * List all tasks
   */
  async listTasks(): Promise<Task[]> {
    const response = await apiClient.get<ListTasksResponse>('/tasks')
    return response.tasks || []
  },

  /**
   * Update a task
   */
  async updateTask(data: UpdateTaskRequest): Promise<Task> {
    const { id, ...updateData } = data
    const response = await apiClient.put<UpdateTaskResponse>(`/tasks/${id}`, updateData)
    return response.task
  },

  /**
   * Delete a task
   */
  async deleteTask(id: string): Promise<boolean> {
    const response = await apiClient.delete<DeleteTaskResponse>(`/tasks/${id}`)
    return response.success
  }
}

