/**
 * Service layer for CreateRequest API operations
 */

import {
  createWorkflowMultipart,
  submitWorkflow,
  updateWorkflow,
  updateWorkflowMultipart,
} from '@/services/workflowApi';
import {
  CreateWorkflowPayload,
  UpdateWorkflowPayload,
} from '../types/createRequest.types';

/**
 * Create a new workflow
 */
export async function createWorkflow(
  payload: CreateWorkflowPayload,
  documents: File[]
): Promise<{ id: string }> {
  const res = await createWorkflowMultipart(
    payload as any,
    documents || [],
    'SUPPORTING'
  );
  return { id: (res as any).id };
}

/**
 * Update an existing workflow
 */
export async function updateWorkflowRequest(
  requestId: string,
  payload: UpdateWorkflowPayload,
  documents: File[],
  documentsToDelete: string[]
): Promise<void> {
  const hasNewFiles = documents && documents.length > 0;
  const hasDeletions = documentsToDelete.length > 0;

  if (hasNewFiles || hasDeletions) {
    await updateWorkflowMultipart(
      requestId,
      payload,
      documents || [],
      documentsToDelete
    );
  } else {
    await updateWorkflow(requestId, payload);
  }
}

/**
 * Submit a workflow
 */
export async function submitWorkflowRequest(requestId: string): Promise<void> {
  await submitWorkflow(requestId);
}

/**
 * Create and submit a workflow in one operation
 */
export async function createAndSubmitWorkflow(
  payload: CreateWorkflowPayload,
  documents: File[]
): Promise<{ id: string }> {
  const result = await createWorkflow(payload, documents);
  await submitWorkflowRequest(result.id);
  return result;
}

/**
 * Update and submit a workflow in one operation
 */
export async function updateAndSubmitWorkflow(
  requestId: string,
  payload: UpdateWorkflowPayload,
  documents: File[],
  documentsToDelete: string[]
): Promise<void> {
  await updateWorkflowRequest(requestId, payload, documents, documentsToDelete);
  await submitWorkflowRequest(requestId);
}

