let squareClient: any = null
let clientError: string | null = null
let isInitializing = false

// Dynamic import function for Square SDK
const importSquareSDK = async () => {
  try {
    // Use dynamic import instead of require
    const squareModule = await import("squareup")
    return squareModule
  } catch (error) {
    console.error("Failed to import Square SDK:", error)
    throw new Error(`Square SDK import failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
  }
}

// Initialize Square client with proper error handling
export const getSquareClient = async () => {
  if (clientError) {
    throw new Error(clientError)
  }

  if (squareClient) {
    return squareClient
  }

  if (isInitializing) {
    // Wait for initialization to complete
    while (isInitializing) {
      await new Promise(resolve => setTimeout(resolve, 100))
    }
    if (squareClient) return squareClient
    if (clientError) throw new Error(clientError)
  }

  isInitializing = true

  try {
    // Validate environment variables first
    if (!process.env.SQUARE_ACCESS_TOKEN) {
      throw new Error("SQUARE_ACCESS_TOKEN environment variable is required")
    }

    if (!process.env.SQUARE_LOCATION_ID) {
      throw new Error("SQUARE_LOCATION_ID environment variable is required")
    }

    console.log("Importing Square SDK...")
    
    // Dynamic import of Square SDK
    const { Client, Environment } = await importSquareSDK()

    console.log("Creating Square client...")

    squareClient = new Client({
      accessToken: process.env.SQUARE_ACCESS_TOKEN,
      environment: process.env.SQUARE_ENVIRONMENT === "production" 
        ? Environment.Production 
        : Environment.Sandbox,
    })

    console.log("Square client created successfully")
    return squareClient

  } catch (error) {
    clientError = error instanceof Error ? error.message : "Failed to initialize Square client"
    console.error("Square client initialization failed:", clientError)
    throw new Error(clientError)
  } finally {
    isInitializing = false
  }
}

// Export location ID with validation
export const getSquareLocationId = () => {
  if (!process.env.SQUARE_LOCATION_ID) {
    throw new Error("SQUARE_LOCATION_ID environment variable is required")
  }
  return process.env.SQUARE_LOCATION_ID
}

// Health check function
export const checkSquareConnection = async () => {
  try {
    console.log("Starting Square connection check...")
    
    const client = await getSquareClient()
    const locationId = getSquareLocationId()
    
    console.log("Testing Square API connection...")
    
    // Try a simple API call to verify connection
    const locationsApi = client.locationsApi
    const response = await locationsApi.retrieveLocation(locationId)
    
    console.log("Square API connection successful")
    
    return { 
      success: true, 
      message: "Square connection verified",
      locationName: response.result.location?.name || "Unknown"
    }
  } catch (error) {
    console.error("Square connection check failed:", error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "Connection failed" 
    }
  }
}

// Reset client (useful for testing)
export const resetSquareClient = () => {
  squareClient = null
  clientError = null
  isInitializing = false
}
