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

// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
// filename is always a hardcoded constant, 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 CONTACT_REQUESTS_FILE = getDataPath('contact-requests.json')

export async function readContactRequests() {
  try {
    const raw = await fs.readFile(CONTACT_REQUESTS_FILE, 'utf-8')
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? parsed : []
  } catch (error) {
    if (error.code === 'ENOENT') return []
    console.error('Fehler beim Lesen der Kontaktanfragen:', error)
    return []
  }
}

export async function writeContactRequests(items) {
  await fs.writeFile(CONTACT_REQUESTS_FILE, JSON.stringify(items, null, 2), 'utf-8')
}

export async function createContactRequest(data) {
  const current = await readContactRequests()
  const now = new Date().toISOString()
  const item = {
    id: randomUUID(),
    createdAt: now,
    updatedAt: now,
    status: 'offen',
    name: data.name,
    email: data.email,
    phone: data.phone || '',
    subject: data.subject,
    message: data.message,
    replies: []
  }
  current.unshift(item)
  await writeContactRequests(current)
  return item
}

export async function addContactReply({ requestId, replyText, responderEmail }) {
  const current = await readContactRequests()
  const index = current.findIndex((r) => r.id === requestId)
  if (index === -1) return null

  const now = new Date().toISOString()
  const request = current[index]
  const replies = Array.isArray(request.replies) ? request.replies : []
  replies.push({
    id: randomUUID(),
    createdAt: now,
    responderEmail: responderEmail || '',
    message: replyText
  })

  current[index] = {
    ...request,
    status: 'beantwortet',
    replies,
    updatedAt: now
  }

  await writeContactRequests(current)
  return current[index]
}

export async function updateContactRequestStatus(requestId, newStatus) {
  const validStatuses = ['offen', 'beantwortet']
  if (!validStatuses.includes(newStatus)) return null

  const current = await readContactRequests()
  const index = current.findIndex((r) => r.id === requestId)
  if (index === -1) return null

  const now = new Date().toISOString()
  current[index] = {
    ...current[index],
    status: newStatus,
    updatedAt: now
  }

  await writeContactRequests(current)
  return current[index]
}
