/**
 * Task API Client
 * Handles task-related API requests
 */

import type { Task } from "@mosaic/shared";
import type { TaskStatus, TaskPriority } from "@mosaic/shared";
import { apiGet, apiPatch, type ApiResponse } from "./client";

export interface TaskFilters {
  status?: TaskStatus;
  priority?: TaskPriority;
  workspaceId?: string;
}

/**
 * Fetch tasks with optional filters
 */
export async function fetchTasks(filters?: TaskFilters): Promise<Task[]> {
  const params = new URLSearchParams();

  // Add filter parameters (not workspace ID - that goes in header)
  if (filters?.status) {
    params.append("status", filters.status);
  }
  if (filters?.priority) {
    params.append("priority", filters.priority);
  }

  const queryString = params.toString();
  const endpoint = queryString ? `/api/tasks?${queryString}` : "/api/tasks";

  // Pass workspaceId via header (X-Workspace-Id) instead of query string
  const response = await apiGet<ApiResponse<Task[]>>(endpoint, filters?.workspaceId);
  return response.data;
}

/**
 * Update a task by ID
 */
export async function updateTask(
  id: string,
  data: Partial<Task>,
  workspaceId?: string
): Promise<Task> {
  const res = await apiPatch<ApiResponse<Task>>(`/api/tasks/${id}`, data, workspaceId);
  return res.data;
}

export interface CreateTaskInput {
  title: string;
  description?: string;
  status?: TaskStatus;
  priority?: TaskPriority;
  dueDate?: string;
  projectId?: string;
}

/**
 * Create a new task
 */
export async function createTask(data: CreateTaskInput, workspaceId?: string): Promise<Task> {
  const { apiPost } = await import("./client");
  const res = await apiPost<ApiResponse<Task>>("/api/tasks", data, workspaceId);
  return res.data;
}
