import { db } from '../db'
import { jsonResponse, errorResponse } from '../utils/cors'

export async function handleSnapshots(req: Request) {
  if (req.method === 'GET') {
    const rows = db.query(
      'SELECT id, name, thumbnail, created_at FROM canvas_snapshots ORDER BY created_at DESC'
    ).all()
    return jsonResponse(rows)
  }

  if (req.method === 'POST') {
    const body = await req.json()
    const id = body.id || `snap-${Date.now()}`
    const stmt = db.prepare(
      'INSERT OR REPLACE INTO canvas_snapshots (id, name, data, thumbnail, created_at) VALUES (?, ?, ?, ?, ?)'
    )
    stmt.run(
      id,
      body.name,
      typeof body.data === 'string' ? body.data : JSON.stringify(body.data),
      body.thumbnail || null,
      body.created_at || Date.now()
    )
    return jsonResponse({ success: true, id })
  }

  return null
}

export async function handleSnapshotById(req: Request, id: string) {
  if (req.method === 'GET') {
    const row = db.query('SELECT * FROM canvas_snapshots WHERE id = ?').get(id) as any
    if (!row) {
      return errorResponse('Snapshot not found', 404)
    }
    return jsonResponse({
      ...row,
      data: JSON.parse(row.data)
    })
  }

  if (req.method === 'DELETE') {
    db.run('DELETE FROM canvas_snapshots WHERE id = ?', [id])
    return jsonResponse({ success: true })
  }

  return null
}
