import { NextResponse } from 'next/server'
import { readFile, unlink } from 'fs/promises'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { visible } from '@/lib/scope'
import { absFromStored } from '@/lib/media'

export const runtime = 'nodejs'

// GET /api/image/:id        → the attachment (WebP for images, raw otherwise)
// GET /api/image/:id?thumb=1 → 400px thumbnail (images; falls back to full)
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const att = await db.attachment.findFirst({ where: { id, ...visible.attachment(session.userId) }, select: { path: true, thumbPath: true, mime: true, name: true } })
  if (!att) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const wantThumb = new URL(req.url).searchParams.get('thumb') === '1'
  const stored = wantThumb && att.thumbPath ? att.thumbPath : att.path
  const buf = await readFile(absFromStored(stored))
  const mime = att.thumbPath ? 'image/webp' : att.mime || 'application/octet-stream' // legacy rows (mime null) are images
  const headers: Record<string, string> = {
    'Content-Type': att.thumbPath ? 'image/webp' : mime,
    'Cache-Control': 'private, max-age=86400',
  }
  // Open non-images in the browser when possible (e.g. PDFs), keep filename.
  if (!att.thumbPath && att.name) headers['Content-Disposition'] = `inline; filename="${att.name.replace(/[^\w.\- ]/g, '_')}"`
  return new NextResponse(new Uint8Array(buf), { headers })
}

// DELETE /api/image/:id — remove an attachment (row + files on disk).
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const att = await db.attachment.findFirst({ where: { id, ...visible.attachment(session.userId) }, select: { path: true, thumbPath: true, thoughtId: true } })
  if (!att) return NextResponse.json({ error: 'not found' }, { status: 404 })

  await db.attachment.delete({ where: { id } })
  if (att.thoughtId) {
    // Touch the thought so the client cache fingerprint moves.
    await db.thought.update({ where: { id: att.thoughtId }, data: { updatedAt: new Date() } }).catch(() => {})
  }
  await Promise.all([
    unlink(absFromStored(att.path)).catch(() => {}),
    att.thumbPath ? unlink(absFromStored(att.thumbPath)).catch(() => {}) : Promise.resolve(),
  ])
  return NextResponse.json({ ok: true })
}
