import fs from 'fs/promises'
import path from 'path'
import { getUserFromToken, verifyToken } from '../../utils/auth.js'

// Handle both dev and production paths
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
// filename is always a hardcoded constant (e.g., 'galerie-metadata.json'), never user input
const getDataPath = (filename) => {
  const cwd = process.cwd()
  if (cwd.endsWith('.output')) {
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    return path.join(cwd, '../server/data', filename)
  }
  // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
  return path.join(cwd, 'server/data', filename)
}

const GALERIE_METADATA = getDataPath('galerie-metadata.json')

async function readGalerieMetadata() {
  try {
    const data = await fs.readFile(GALERIE_METADATA, 'utf-8')
    return JSON.parse(data)
  } catch (error) {
    if (error.code === 'ENOENT') {
      return []
    }
    throw error
  }
}

export default defineEventHandler(async (event) => {
  try {
    // Prüfe ob Benutzer eingeloggt ist
    let isLoggedIn = false
    const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace('Bearer ', '')
    
    if (token) {
      const decoded = verifyToken(token)
      if (decoded) {
        const user = await getUserFromToken(token)
        if (user && user.active) {
          isLoggedIn = true
        }
      }
    }

    const metadata = await readGalerieMetadata()

    // Filtere Bilder basierend auf Sichtbarkeit
    const visibleImages = metadata.filter(image => {
      // Öffentliche Bilder sind für alle sichtbar
      if (image.isPublic) return true
      // Private Bilder nur für eingeloggte Mitglieder
      return isLoggedIn
    })

    // Sortiere nach Upload-Datum (neueste zuerst)
    visibleImages.sort((a, b) => new Date(b.uploadedAt) - new Date(a.uploadedAt))

    // Pagination
    const page = parseInt(getQuery(event).page) || 1
    const perPage = 10
    const start = (page - 1) * perPage
    const end = start + perPage
    const paginatedImages = visibleImages.slice(start, end)

    return {
      success: true,
      images: paginatedImages.map(img => ({
        id: img.id,
        title: img.title,
        description: img.description,
        isPublic: img.isPublic,
        uploadedAt: img.uploadedAt,
        previewFilename: img.previewFilename
      })),
      pagination: {
        page,
        perPage,
        total: visibleImages.length,
        totalPages: Math.ceil(visibleImages.length / perPage)
      }
    }

  } catch (error) {
    console.error('Fehler beim Laden der Galerie:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Laden der Galerie'
    })
  }
})

