import { TEST_CONFIG } from 'playwright.config'

import { getBackendMode } from './get-backend-mode'

export async function resetData(): Promise<{ status: number; message: string }> {
  // Check the backend mode
  const backendMode = await getBackendMode()
  if (backendMode !== 'stateful') {
    console.warn('Backend is in stateless mode. Skipping data reset.')
    // Return a 204 status code to indicate that the request was understood and accepted,
    // but no action was taken (e.g., skipping the reset operation in stateless mode).
    return { status: 204, message: 'Backend is in stateless mode. Skipping data reset.' }
  }

  if (!TEST_CONFIG.apiURL) {
    throw new Error('API_URL environment variable not set')
  }

  // Use the reset endpoint to reset the test data
  const response = await fetch(`${TEST_CONFIG.apiURL}/test/reset`, { method: 'PUT' })

  // Handle different status codes
  switch (response.status) {
    case 200: // Success
      console.log('Reset data successfully')
      return { status: 200, message: 'Reset data successfully' }

    case 404: // Not Found
      console.log('Reset endpoint not available: 404 Not Found')
      return { status: 404, message: 'Reset endpoint not available: 404 Not Found' }

    default: // Other errors
      return {
        status: response.status,
        message: `Reset data failed with status ${response.status}: ${response.statusText}`,
      }
  }
}
