import { promises as fs } from 'fs'
import path from 'path'
import { randomUUID } from 'crypto'

// 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., 'news.json'), never user input
const getDataPath = (filename) => {
  const cwd = process.cwd()
  
  // In production (.output/server), working dir is .output
  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)
  }
  
  // In development, working dir is project root
  // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
  return path.join(cwd, 'server/data', filename)
}

const NEWS_FILE = getDataPath('news.json')

// Read news from file
export async function readNews() {
  try {
    const data = await fs.readFile(NEWS_FILE, 'utf-8')
    return JSON.parse(data)
  } catch (error) {
    if (error.code === 'ENOENT') {
      return []
    }
    console.error('Fehler beim Lesen der News:', error)
    return []
  }
}

// Write news to file
export async function writeNews(news) {
  try {
    await fs.writeFile(NEWS_FILE, JSON.stringify(news, null, 2), 'utf-8')
    return true
  } catch (error) {
    console.error('Fehler beim Schreiben der News:', error)
    return false
  }
}

// Get news by ID
export async function getNewsById(id) {
  const news = await readNews()
  return news.find(n => n.id === id)
}

// Add or update news
export async function saveNews(newsData) {
  const newsList = await readNews()
  
  if (newsData.id) {
    // Update existing
    const index = newsList.findIndex(n => n.id === newsData.id)
    if (index !== -1) {
      newsList[index] = {
        ...newsList[index],
        ...newsData,
        updated: new Date().toISOString()
      }
    } else {
      throw new Error('News nicht gefunden')
    }
  } else {
    // Add new - use UUID for guaranteed uniqueness
    const newItem = {
      ...newsData,
      id: randomUUID(), // Cryptographically secure unique ID
      isPublic: newsData.isPublic || false, // Default to internal
      created: new Date().toISOString(),
      updated: new Date().toISOString()
    }
    newsList.unshift(newItem) // Add to beginning
  }
  
  await writeNews(newsList)
  return true
}

// Delete news
export async function deleteNews(id) {
  const newsList = await readNews()
  const filtered = newsList.filter(n => n.id !== id)
  await writeNews(filtered)
  return true
}

