import React from 'react'
import { SDKApiClient, getSDKApiClient } from './api-client'
import { CustomerType, ProjectInfo } from './types'

// =============================================================================
// PROJECT MANAGEMENT HELPERS
// =============================================================================

/**
 * Ensures an API client is available. If the ref is null and backend sync is
 * enabled, lazily initialises one. Returns the client or throws.
 */
export function ensureApiClient(
  apiClientRef: React.MutableRefObject<SDKApiClient | null>,
  enableBackendSync: boolean,
  tenantId: string,
  projectId?: string
): SDKApiClient {
  if (!apiClientRef.current && enableBackendSync) {
    apiClientRef.current = getSDKApiClient(tenantId, projectId)
  }
  if (!apiClientRef.current) {
    throw new Error('Backend sync not enabled')
  }
  return apiClientRef.current
}

export async function createProjectApi(
  apiClient: SDKApiClient,
  name: string,
  customerType: CustomerType,
  copyFromProjectId?: string
): Promise<ProjectInfo> {
  return apiClient.createProject({
    name,
    customer_type: customerType,
    copy_from_project_id: copyFromProjectId,
  })
}

export async function listProjectsApi(
  apiClient: SDKApiClient
): Promise<ProjectInfo[]> {
  const result = await apiClient.listProjects()
  return result.projects
}

export async function archiveProjectApi(
  apiClient: SDKApiClient,
  archiveId: string
): Promise<void> {
  await apiClient.archiveProject(archiveId)
}

export async function restoreProjectApi(
  apiClient: SDKApiClient,
  restoreId: string
): Promise<ProjectInfo> {
  return apiClient.restoreProject(restoreId)
}

export async function permanentlyDeleteProjectApi(
  apiClient: SDKApiClient,
  deleteId: string
): Promise<void> {
  await apiClient.permanentlyDeleteProject(deleteId)
}
