<script setup>
definePageMeta({
  title: "API Test Page"
});

const message = ref('');
const selectedFile = ref(null);
const isUploading = ref(false);

async function testApi() {
  try {
    const response = await $fetch('/api/test/test-response', {
      method: 'POST'
    });
    message.value = JSON.stringify(response, null, 2);
  } catch (error) {
    message.value = 'Error: ' + error.message;
  }
}

async function handleFileUpload() {
  if (!selectedFile.value) {
    message.value = 'Please select a file first';
    return;
  }

  try {
    isUploading.value = true;
    message.value = 'Uploading file...';

    const formData = new FormData();
    formData.append('fileName', selectedFile.value.name);
    formData.append('file', selectedFile.value);

    const response = await $fetch('/api/test/test-response', {
      method: 'POST',
      body: formData
    });

    message.value = JSON.stringify(response, null, 2);
  } catch (error) {
    message.value = 'Error: ' + error.message;
  } finally {
    isUploading.value = false;
  }
}

function handleFileSelect(event) {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file;
    message.value = `Selected file: ${file.name} (${formatFileSize(file.size)})`;
  }
}

function formatFileSize(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
</script>

<template>
  <div class="flex flex-col items-center justify-center min-h-screen p-4 space-y-6">
    <!-- File Upload Section -->
    <div class="w-full max-w-md space-y-4">
      <div class="flex flex-col items-center space-y-4">
        <input
          type="file"
          @change="handleFileSelect"
          class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
        />
        <button
          @click="handleFileUpload"
          :disabled="!selectedFile || isUploading"
          class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors disabled:bg-blue-300 disabled:cursor-not-allowed w-full"
        >
          {{ isUploading ? 'Uploading...' : 'Upload File' }}
        </button>
      </div>
    </div>

    <!-- Test API Button -->
    <button
      @click="testApi"
      class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
    >
      Test API
    </button>
    
    <!-- Response Message -->
    <pre v-if="message" class="mt-4 p-4 bg-gray-100 rounded w-full max-w-md overflow-x-auto">{{ message }}</pre>
  </div>
</template> 