export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import * as fs from 'fs'

const DATA_DIR = fs.existsSync('/data') ? '/data' : '/tmp'
const NOTES_PATH = `${DATA_DIR}/tablet-notes.json`

interface Note {
  id: string
  type: 'note' | 'shopping'
  title: string
  items?: { id: string; text: string; done: boolean }[]
  text?: string
  color: string
  pinDate: string | null
  createdAt: string
  updatedAt: string
}

function loadNotes(): Note[] {
  try {
    if (fs.existsSync(NOTES_PATH)) {
      return JSON.parse(fs.readFileSync(NOTES_PATH, 'utf-8'))
    }
  } catch {}
  return []
}

function saveNotes(notes: Note[]) {
  fs.writeFileSync(NOTES_PATH, JSON.stringify(notes, null, 2))
}

export async function GET() {
  return NextResponse.json({ notes: loadNotes() })
}

export async function POST(req: Request) {
  const body = await req.json()
  const notes = loadNotes()
  const note: Note = {
    id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
    type: body.type || 'note',
    title: body.title || '',
    items: body.type === 'shopping' ? [] : undefined,
    text: body.type === 'note' ? '' : undefined,
    color: body.color || '#6366f1',
    pinDate: body.pinDate || null,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }
  notes.unshift(note)
  saveNotes(notes)
  return NextResponse.json({ note })
}

export async function PUT(req: Request) {
  const body = await req.json()
  const { id, ...updates } = body
  if (!id) return NextResponse.json({ error: 'id required' }, { status: 400 })

  const notes = loadNotes()
  const idx = notes.findIndex(n => n.id === id)
  if (idx === -1) return NextResponse.json({ error: 'not found' }, { status: 404 })

  notes[idx] = { ...notes[idx], ...updates, updatedAt: new Date().toISOString() }
  saveNotes(notes)
  return NextResponse.json({ note: notes[idx] })
}

export async function DELETE(req: Request) {
  const { searchParams } = new URL(req.url)
  const id = searchParams.get('id')
  if (!id) return NextResponse.json({ error: 'id required' }, { status: 400 })

  const notes = loadNotes()
  const filtered = notes.filter(n => n.id !== id)
  saveNotes(filtered)
  return NextResponse.json({ success: true })
}
