import fs from 'fs/promises'
import path from 'path'

export default defineEventHandler(async (event) => {
  try {
    const pageData = await readBody(event)
    
    if (!pageData.name || !pageData.path) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Page name and path are required'
      })
    }
    
    // Generate Vue file content
    const vueTemplate = `<template>
  <v-container>
    <v-row>
      <v-col cols="12">
        <v-card elevation="2">
          <v-card-title class="d-flex align-center">
            <v-icon left v-if="pageData.content?.icon">{{ pageData.content.icon }}</v-icon>
            <span>{{ pageData.metadata?.title || 'Page Title' }}</span>
          </v-card-title>
          
          <v-card-text>
            <p>{{ pageData.metadata?.description || 'Page description goes here.' }}</p>
            
            <!-- Add your custom content here -->
            <v-alert type="info" variant="tonal">
              This page was automatically generated from the menu system.
            </v-alert>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup lang="ts">
definePageMeta({
  title: '${pageData.metadata?.title || 'Generated Page'}',
  description: '${pageData.metadata?.description || ''}',
  layout: 'default'
})

// Page data
const pageData = ${JSON.stringify(pageData, null, 2)}
</script>

<style scoped>
/* Add your custom styles here */
</style>
`

    // Determine file path
    const fileName = `${pageData.name.toLowerCase().replace(/\s+/g, '-')}.vue`
    const pagesDir = path.join(process.cwd(), 'matdash', 'pages')
    const filePath = path.join(pagesDir, fileName)
    
    // Ensure pages directory exists
    await fs.mkdir(pagesDir, { recursive: true })
    
    // Write Vue file
    await fs.writeFile(filePath, vueTemplate)
    
    // Save page data to JSON
    const dataPath = path.join(process.cwd(), 'matdash', 'data', 'pages.json')
    let pagesData
    
    try {
      const fileContent = await fs.readFile(dataPath, 'utf-8')
      pagesData = JSON.parse(fileContent)
    } catch {
      pagesData = { pages: [] }
    }
    
    // Add or update page data
    const existingIndex = pagesData.pages.findIndex((page: any) => page.path === pageData.path)
    const pageRecord = {
      ...pageData,
      id: pageData.id || `page-${Date.now()}`,
      fileName,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    if (existingIndex >= 0) {
      pagesData.pages[existingIndex] = pageRecord
    } else {
      pagesData.pages.push(pageRecord)
    }
    
    await fs.writeFile(dataPath, JSON.stringify(pagesData, null, 2))
    
    return {
      success: true,
      data: {
        fileName,
        filePath: filePath.replace(process.cwd(), ''),
        pageData: pageRecord
      }
    }
  } catch (error) {
    console.error('Error generating page:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to generate page'
    })
  }
})
