import { auth } from '@/auth'
import { db } from '@/lib/db'
import { machines } from '@/lib/db/schema'
import { eq, and } from 'drizzle-orm'
import { NextRequest, NextResponse } from 'next/server'

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth()
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id } = await params

  // Only delete if the machine belongs to the requesting user
  const result = await db
    .delete(machines)
    .where(and(eq(machines.id, id), eq(machines.userId, session.user.id)))
    .returning({ id: machines.id })

  if (!result[0]) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 })
  }

  return NextResponse.json({ success: true })
}
