<template>
    <div class="min-h-screen bg-gray-50 py-8">
      <div class="max-w-4xl mx-auto px-4">
        <h1 class="text-3xl font-bold text-gray-900 mb-8">API Testing Page</h1>
        
        <!-- Test Application Creation -->
        <div class="bg-white rounded-lg shadow p-6 mb-6">
          <h2 class="text-xl font-semibold mb-4">Test Application Creation</h2>
          
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
            <button 
              @click="testCreateApp('oauth2')"
              :disabled="loading"
              class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
            >
              Test OAuth2 App
            </button>
            
            <button 
              @click="testCreateApp('ldap')"
              :disabled="loading"
              class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded disabled:opacity-50"
            >
              Test LDAP App
            </button>
            
            <button 
              @click="testCreateApp('saml')"
              :disabled="loading"
              class="bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded disabled:opacity-50"
            >
              Test SAML App
            </button>
            
            <button 
              @click="testCreateApp('proxy')"
              :disabled="loading"
              class="bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded disabled:opacity-50"
            >
              Test Proxy App
            </button>
          </div>
          
          <div class="mb-4">
            <button 
              @click="testListApps"
              :disabled="loading"
              class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded disabled:opacity-50 mr-2"
            >
              List Applications
            </button>
            
            <button 
              @click="testAuthentikConnection"
              :disabled="loading"
              class="bg-indigo-500 hover:bg-indigo-600 text-white px-4 py-2 rounded disabled:opacity-50"
            >
              Test Authentik Connection
            </button>
          </div>
          
          <div v-if="loading" class="text-blue-600 mb-4">
            ⏳ {{ loadingMessage }}
          </div>
        </div>
        
        <!-- Results Display -->
        <div class="bg-white rounded-lg shadow p-6">
          <h2 class="text-xl font-semibold mb-4">Results</h2>
          
          <div v-if="result" class="mb-4">
            <div class="flex items-center mb-2">
              <span class="text-sm font-medium text-gray-500 mr-2">Status:</span>
              <span :class="result.success ? 'text-green-600' : 'text-red-600'" class="font-medium">
                {{ result.success ? '✅ Success' : '❌ Error' }}
              </span>
            </div>
            
            <div class="bg-gray-50 rounded p-4 overflow-auto">
              <pre class="text-sm">{{ JSON.stringify(result.data, null, 2) }}</pre>
            </div>
          </div>
          
          <div v-if="!result" class="text-gray-500 text-center py-8">
            Click a test button above to see results here
          </div>
          
          <button 
            v-if="result" 
            @click="result = null"
            class="mt-4 bg-gray-300 hover:bg-gray-400 text-gray-700 px-4 py-2 rounded"
          >
            Clear Results
          </button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  // State
  const loading = ref(false)
  const loadingMessage = ref('')
  const result = ref(null)
  
  // Test functions
  const testCreateApp = async (providerType) => {
    loading.value = true
    loadingMessage.value = `Creating ${providerType.toUpperCase()} application...`
    
    try {
      const timestamp = Date.now()
      const testApp = {
        name: `Test ${providerType.toUpperCase()} ${timestamp}`,
        slug: `test-${providerType}-${timestamp}`,
        meta_description: `Test ${providerType} application for debugging`,
        meta_launch_url: 'http://localhost:5000/test',
        meta_publisher: 'IT Department - Test',
        setupType: 'web-app',
        providerType: providerType
      }
      
      console.log(`🧪 Testing ${providerType} application creation:`, testApp)
      
      const response = await $fetch('/api/applications', {
        method: 'POST',
        body: testApp
      })
      
      result.value = {
        success: true,
        data: {
          message: `${providerType.toUpperCase()} application created successfully!`,
          application: response,
          requestData: testApp
        }
      }
      
    } catch (error) {
      console.error(`❌ ${providerType} test failed:`, error)
      result.value = {
        success: false,
        data: {
          error: error.message,
          statusCode: error.statusCode,
          details: error.data,
          requestData: testApp
        }
      }
    } finally {
      loading.value = false
      loadingMessage.value = ''
    }
  }
  
  const testListApps = async () => {
    loading.value = true
    loadingMessage.value = 'Fetching applications list...'
    
    try {
      const response = await $fetch('/api/applications')
      
      result.value = {
        success: true,
        data: {
          message: 'Applications fetched successfully!',
          count: response.results?.length || 0,
          applications: response.results || []
        }
      }
      
    } catch (error) {
      console.error('❌ List apps test failed:', error)
      result.value = {
        success: false,
        data: {
          error: error.message,
          statusCode: error.statusCode,
          details: error.data
        }
      }
    } finally {
      loading.value = false
      loadingMessage.value = ''
    }
  }
  
  const testAuthentikConnection = async () => {
    loading.value = true
    loadingMessage.value = 'Testing Authentik connection...'
    
    try {
      const response = await $fetch('/api/test-authentik')
      
      result.value = {
        success: true,
        data: {
          message: 'Authentik connection test successful!',
          connectionTest: response
        }
      }
      
    } catch (error) {
      console.error('❌ Authentik connection test failed:', error)
      result.value = {
        success: false,
        data: {
          error: error.message,
          statusCode: error.statusCode,
          details: error.data
        }
      }
    } finally {
      loading.value = false
      loadingMessage.value = ''
    }
  }
  
  // Page metadata
  useHead({
    title: 'API Testing - CorradAF RBAC'
  })
  </script>