import { api } from './api';
import type {
  VikunjaTasksResponse,
  VikunjaProjectsResponse,
  VikunjaTask,
} from '../types/vikunja.types';

interface ApiResponse<T> {
  success: boolean;
  data: T;
  configured: boolean;
}

export const vikunjaApi = {
  getMyTasks(): Promise<VikunjaTasksResponse> {
    return api
      .get<ApiResponse<VikunjaTasksResponse['data']> & { vikunjaUrl?: string }>('/api/vikunja/tasks')
      .then((r) => ({ configured: r.data.configured, data: r.data.data, vikunjaUrl: r.data.vikunjaUrl }));
  },

  getOverdueTasks(): Promise<VikunjaTasksResponse> {
    return api
      .get<ApiResponse<VikunjaTasksResponse['data']>>('/api/vikunja/overdue')
      .then((r) => ({ configured: r.data.configured, data: r.data.data }));
  },

  getProjects(): Promise<VikunjaProjectsResponse> {
    return api
      .get<ApiResponse<VikunjaProjectsResponse['data']>>('/api/vikunja/projects')
      .then((r) => ({ configured: r.data.configured, data: r.data.data }));
  },

  createTask(projectId: number, title: string, dueDate?: string): Promise<{ data: VikunjaTask }> {
    return api
      .post<{ success: boolean; data: VikunjaTask }>('/api/vikunja/tasks', {
        projectId,
        title,
        dueDate,
      })
      .then((r) => ({ data: r.data.data }));
  },
};
