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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import type {
  ActivityStatsResponse,
  CreateFlowRequest,
  DelayedJobInfo,
  FlowNode,
  FlowSummary,
  JobInfo,
  JobStatus,
  MetricsResponse,
  OverviewStats,
  PaginatedResponse,
  QueueInfo,
  RunInfoList,
  SchedulerInfo,
  SearchResult,
} from "@/core/types";

const API_BASE = "./api";

// Default timeout of 60 seconds for API requests
const DEFAULT_TIMEOUT = 60000;

// Extended timeout for heavy operations (120 seconds)
const EXTENDED_TIMEOUT = 120000;

interface FetchOptions extends Omit<RequestInit, "signal"> {
  timeout?: number;
  signal?: AbortSignal; // React Query's signal for cancellation
}

async function fetchJson<T>(url: string, options?: FetchOptions): Promise<T> {
  const {
    timeout = DEFAULT_TIMEOUT,
    signal: externalSignal,
    ...fetchOptions
  } = options || {};

  // Create AbortController for timeout
  const timeoutController = new AbortController();
  const timeoutId = setTimeout(() => timeoutController.abort(), timeout);

  // Combine signals: React Query's signal (for unmount) + timeout signal
  // Use AbortSignal.any if available (modern browsers), otherwise just use timeout
  let combinedSignal: AbortSignal;
  if (externalSignal && "any" in AbortSignal) {
    combinedSignal = AbortSignal.any([
      externalSignal,
      timeoutController.signal,
    ]);
  } else if (externalSignal) {
    // Fallback: link external signal to our controller
    if (externalSignal.aborted) {
      timeoutController.abort();
    } else {
      externalSignal.addEventListener("abort", () => timeoutController.abort());
    }
    combinedSignal = timeoutController.signal;
  } else {
    combinedSignal = timeoutController.signal;
  }

  try {
    const response = await fetch(url, {
      ...fetchOptions,
      signal: combinedSignal,
      headers: {
        "Content-Type": "application/json",
        ...fetchOptions?.headers,
      },
    });

    if (!response.ok) {
      const error = await response.json().catch(() => ({}));
      throw new Error(error.error || `HTTP ${response.status}`);
    }

    return response.json();
  } catch (error) {
    if (error instanceof Error && error.name === "AbortError") {
      // Check if it was our timeout or external cancellation
      if (externalSignal?.aborted) {
        throw error; // Let React Query handle the cancellation
      }
      throw new Error(`Request timed out after ${timeout / 1000}s`);
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}

export const api = {
  /**
   * Clear all server-side caches (for user-initiated refresh)
   */
  async refresh(): Promise<{ success: boolean }> {
    return fetchJson(`${API_BASE}/refresh`, { method: "POST" });
  },

  /**
   * Get dashboard overview stats (longer timeout as it scans all queues)
   */
  async getOverview(signal?: AbortSignal): Promise<OverviewStats> {
    return fetchJson(`${API_BASE}/overview`, {
      signal,
      timeout: EXTENDED_TIMEOUT,
    });
  },

  /**
   * Get quick job counts for smart polling (lightweight, cached)
   */
  async getCounts(signal?: AbortSignal): Promise<{
    waiting: number;
    active: number;
    completed: number;
    failed: number;
    delayed: number;
    total: number;
    timestamp: number;
  }> {
    return fetchJson(`${API_BASE}/counts`, { signal });
  },

  /**
   * Get just queue names (fast, no counts)
   */
  async getQueueNames(signal?: AbortSignal): Promise<string[]> {
    return fetchJson(`${API_BASE}/queue-names`, { signal });
  },

  /**
   * Get all queues with counts
   */
  async getQueues(signal?: AbortSignal): Promise<QueueInfo[]> {
    return fetchJson(`${API_BASE}/queues`, { signal });
  },

  /**
   * Get 24-hour metrics (longer timeout as it scans all queues)
   */
  async getMetrics(signal?: AbortSignal): Promise<MetricsResponse> {
    return fetchJson(`${API_BASE}/metrics`, {
      signal,
      timeout: EXTENDED_TIMEOUT,
    });
  },

  /**
   * Get 7-day activity stats for the timeline (cached server-side)
   */
  async getActivityStats(signal?: AbortSignal): Promise<ActivityStatsResponse> {
    return fetchJson(`${API_BASE}/activity`, {
      signal,
      timeout: EXTENDED_TIMEOUT,
    });
  },

  /**
   * Get jobs for a queue
   */
  async getJobs(
    queueName: string,
    options?: {
      status?: JobStatus;
      limit?: number;
      cursor?: string;
      sort?: string; // format: "field:direction"
    },
  ): Promise<PaginatedResponse<JobInfo>> {
    const params = new URLSearchParams();
    if (options?.status) params.set("status", options.status);
    if (options?.limit) params.set("limit", String(options.limit));
    if (options?.cursor) params.set("cursor", options.cursor);
    if (options?.sort) params.set("sort", options.sort);

    const query = params.toString();
    return fetchJson(
      `${API_BASE}/queues/${encodeURIComponent(queueName)}/jobs${query ? `?${query}` : ""}`,
    );
  },

  /**
   * Get a single job
   */
  async getJob(queueName: string, jobId: string): Promise<JobInfo> {
    return fetchJson(
      `${API_BASE}/jobs/${encodeURIComponent(queueName)}/${encodeURIComponent(jobId)}`,
    );
  },

  /**
   * Retry a job
   */
  async retryJob(queueName: string, jobId: string): Promise<void> {
    await fetchJson(
      `${API_BASE}/jobs/${encodeURIComponent(queueName)}/${encodeURIComponent(jobId)}/retry`,
      { method: "POST" },
    );
  },

  /**
   * Remove a job
   */
  async removeJob(queueName: string, jobId: string): Promise<void> {
    await fetchJson(
      `${API_BASE}/jobs/${encodeURIComponent(queueName)}/${encodeURIComponent(jobId)}/remove`,
      { method: "POST" },
    );
  },

  /**
   * Promote a delayed job
   */
  async promoteJob(queueName: string, jobId: string): Promise<void> {
    await fetchJson(
      `${API_BASE}/jobs/${encodeURIComponent(queueName)}/${encodeURIComponent(jobId)}/promote`,
      { method: "POST" },
    );
  },

  /**
   * Search jobs
   */
  async search(
    query: string,
    limit?: number,
  ): Promise<{ results: SearchResult[] }> {
    const params = new URLSearchParams({ q: query });
    if (limit) params.set("limit", String(limit));
    return fetchJson(`${API_BASE}/search?${params.toString()}`);
  },

  /**
   * Clean jobs from a queue
   */
  async cleanJobs(
    queueName: string,
    status: "completed" | "failed",
    grace?: number,
  ): Promise<{ removed: number }> {
    return fetchJson(
      `${API_BASE}/queues/${encodeURIComponent(queueName)}/clean`,
      {
        method: "POST",
        body: JSON.stringify({ status, grace }),
      },
    );
  },

  /**
   * Get dashboard config
   */
  async getConfig(): Promise<{
    title: string;
    logo?: string;
    readonly: boolean;
    queues: string[];
    tags: string[];
  }> {
    return fetchJson("./config");
  },

  /**
   * Get unique values for a tag field
   */
  async getTagValues(
    field: string,
    limit?: number,
  ): Promise<{ field: string; values: { value: string; count: number }[] }> {
    const params = new URLSearchParams();
    if (limit) params.set("limit", String(limit));
    const query = params.toString();
    return fetchJson(
      `${API_BASE}/tags/${encodeURIComponent(field)}/values${query ? `?${query}` : ""}`,
    );
  },

  /**
   * Get all runs (jobs across all queues, longer timeout)
   */
  async getRuns(
    options?: {
      limit?: number;
      cursor?: string;
      sort?: string; // format: "field:direction"
      status?: JobStatus;
      tags?: Record<string, string>;
      text?: string;
      timeRange?: { start: number; end: number };
    },
    signal?: AbortSignal,
  ): Promise<PaginatedResponse<RunInfoList>> {
    const params = new URLSearchParams();
    if (options?.limit) params.set("limit", String(options.limit));
    if (options?.cursor) params.set("cursor", options.cursor);
    if (options?.sort) params.set("sort", options.sort);
    if (options?.status) params.set("status", options.status);
    if (options?.tags && Object.keys(options.tags).length > 0) {
      params.set("tags", JSON.stringify(options.tags));
    }
    if (options?.text) params.set("q", options.text);
    if (options?.timeRange) {
      params.set("from", String(options.timeRange.start));
      params.set("to", String(options.timeRange.end));
    }

    const query = params.toString();
    return fetchJson(`${API_BASE}/runs${query ? `?${query}` : ""}`, {
      signal,
      timeout: EXTENDED_TIMEOUT,
    });
  },

  /**
   * Get schedulers (repeatable and delayed jobs)
   */
  async getSchedulers(options?: {
    repeatableSort?: string; // format: "field:direction"
    delayedSort?: string; // format: "field:direction"
  }): Promise<{
    repeatable: SchedulerInfo[];
    delayed: DelayedJobInfo[];
  }> {
    const params = new URLSearchParams();
    if (options?.repeatableSort)
      params.set("repeatableSort", options.repeatableSort);
    if (options?.delayedSort) params.set("delayedSort", options.delayedSort);

    const query = params.toString();
    return fetchJson(`${API_BASE}/schedulers${query ? `?${query}` : ""}`);
  },

  /**
   * Get repeatable schedulers
   */
  async getRepeatableSchedulers(sort?: string): Promise<SchedulerInfo[]> {
    const { repeatable } = await this.getSchedulers({ repeatableSort: sort });
    return repeatable;
  },

  /**
   * Get delayed schedulers
   */
  async getDelayedSchedulers(sort?: string): Promise<DelayedJobInfo[]> {
    const { delayed } = await this.getSchedulers({ delayedSort: sort });
    return delayed;
  },

  /**
   * Enqueue a test job
   */
  async testJob(request: {
    queueName: string;
    name: string;
    data: unknown;
    delay?: number;
  }): Promise<{ id: string }> {
    return fetchJson(`${API_BASE}/test`, {
      method: "POST",
      body: JSON.stringify(request),
    });
  },

  /**
   * Clean queue jobs by status
   */
  async cleanQueue(
    queueName: string,
    status: JobStatus,
    grace?: number,
  ): Promise<{ removed: number }> {
    return fetchJson(
      `${API_BASE}/queues/${encodeURIComponent(queueName)}/clean`,
      {
        method: "POST",
        body: JSON.stringify({ status, grace }),
      },
    );
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // Bulk Operations
  // ─────────────────────────────────────────────────────────────────────────────

  /**
   * Retry multiple jobs
   */
  async bulkRetry(
    jobs: { queueName: string; jobId: string }[],
  ): Promise<{ success: number; failed: number }> {
    return fetchJson(`${API_BASE}/bulk/retry`, {
      method: "POST",
      body: JSON.stringify({ jobs }),
    });
  },

  /**
   * Delete multiple jobs
   */
  async bulkDelete(
    jobs: { queueName: string; jobId: string }[],
  ): Promise<{ success: number; failed: number }> {
    return fetchJson(`${API_BASE}/bulk/delete`, {
      method: "POST",
      body: JSON.stringify({ jobs }),
    });
  },

  /**
   * Promote multiple delayed jobs
   */
  async bulkPromote(
    jobs: { queueName: string; jobId: string }[],
  ): Promise<{ success: number; failed: number }> {
    return fetchJson(`${API_BASE}/bulk/promote`, {
      method: "POST",
      body: JSON.stringify({ jobs }),
    });
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // Queue Control (Pause/Resume)
  // ─────────────────────────────────────────────────────────────────────────────

  /**
   * Pause a queue
   */
  async pauseQueue(
    queueName: string,
  ): Promise<{ success: boolean; paused: boolean }> {
    return fetchJson(
      `${API_BASE}/queues/${encodeURIComponent(queueName)}/pause`,
      { method: "POST" },
    );
  },

  /**
   * Resume a queue
   */
  async resumeQueue(
    queueName: string,
  ): Promise<{ success: boolean; paused: boolean }> {
    return fetchJson(
      `${API_BASE}/queues/${encodeURIComponent(queueName)}/resume`,
      { method: "POST" },
    );
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // Flow Operations
  // ─────────────────────────────────────────────────────────────────────────────

  /**
   * Get all flows (longer timeout as it scans all queues)
   */
  async getFlows(
    limit?: number,
    signal?: AbortSignal,
  ): Promise<{ flows: FlowSummary[] }> {
    const params = new URLSearchParams();
    if (limit) params.set("limit", String(limit));
    const query = params.toString();
    return fetchJson(`${API_BASE}/flows${query ? `?${query}` : ""}`, {
      signal,
      timeout: EXTENDED_TIMEOUT,
    });
  },

  /**
   * Get a single flow tree
   */
  async getFlow(queueName: string, jobId: string): Promise<FlowNode> {
    return fetchJson(
      `${API_BASE}/flows/${encodeURIComponent(queueName)}/${encodeURIComponent(jobId)}`,
    );
  },

  /**
   * Create a new flow
   */
  async createFlow(request: CreateFlowRequest): Promise<{ id: string }> {
    return fetchJson(`${API_BASE}/flows`, {
      method: "POST",
      body: JSON.stringify(request),
    });
  },
};