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 PATCH(
  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
  const body = await request.json()

  const updates: Record<string, unknown> = {}
  if (body.name !== undefined) updates.name = String(body.name).slice(0, 255)
  if (body.notes !== undefined) updates.notes = body.notes ? String(body.notes) : null
  if (body.tags !== undefined) updates.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
  if (body.groupId !== undefined) updates.groupId = body.groupId || null

  if (Object.keys(updates).length === 0) {
    return NextResponse.json({ error: 'Nothing to update' }, { status: 400 })
  }

  const result = await db
    .update(machines)
    .set(updates)
    .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 })
}

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 })
}
