// Version service layer for workflow versioning operations

import { apiRequest } from './api';
import {
  Version,
  PublishResponse,
  RestoreResponse,
  MakeVersionLiveResponse,
  WorkflowVersionStatus,
} from '../types/workflow';

/**
 * Get version history for a workflow
 */
export async function getVersions(
  workflowId: number,
  limit: number = 10,
  offset: number = 0,
): Promise<Version[]> {
  const params = new URLSearchParams();
  params.append('limit', limit.toString());
  params.append('offset', offset.toString());

  return apiRequest<Version[]>(`/workflows/${workflowId}/versions?${params.toString()}`, {
    method: 'GET',
  });
}

/**
 * Get a specific version
 */
export async function getVersion(workflowId: number, versionId: number): Promise<Version> {
  return apiRequest<Version>(`/workflows/${workflowId}/versions/${versionId}`, { method: 'GET' });
}

/**
 * Publish the current draft as a new version
 */
export async function publishWorkflow(
  workflowId: number,
  notes?: string,
): Promise<PublishResponse> {
  return apiRequest<PublishResponse>(`/workflows/${workflowId}/publish`, {
    method: 'POST',
    body: JSON.stringify({ notes: notes || '' }),
  });
}

/**
 * Restore a previous version (loads its config as the current draft)
 */
export async function restoreVersion(
  workflowId: number,
  versionId: number,
): Promise<RestoreResponse> {
  return apiRequest<RestoreResponse>(`/workflows/${workflowId}/versions/${versionId}/restore`, {
    method: 'POST',
  });
}

/**
 * Get workflow publishing status
 */
export async function getWorkflowStatus(workflowId: number): Promise<WorkflowVersionStatus> {
  return apiRequest<WorkflowVersionStatus>(`/workflows/${workflowId}/status`, { method: 'GET' });
}

/**
 * Make a specific version live (sets it as the currently published version)
 */
export async function makeVersionLive(
  workflowId: number,
  versionId: number,
): Promise<MakeVersionLiveResponse> {
  return apiRequest<MakeVersionLiveResponse>(
    `/workflows/${workflowId}/versions/${versionId}/make-live`,
    { method: 'POST' },
  );
}

// Export all functions as a service object
export const versionService = {
  getVersions,
  getVersion,
  publishWorkflow,
  restoreVersion,
  getWorkflowStatus,
  makeVersionLive,
};
