import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { owned, visible } from '@/lib/scope'
import { logActivity } from '@/lib/activity'

export const runtime = 'nodejs'

// DELETE /api/focus/:pinId — unpin from Focus. The underlying reminder or list
// is left completely untouched (toggling/renaming happen against the canonical
// /api/reminders and /api/checklist-items endpoints).
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 { count } = await db.focusPin.deleteMany({ where: { id, ...visible.focusPin(session.userId) } })
  if (count) logActivity(session.userId, 'focus.unpinned', 'Removed an item from Focus')
  return NextResponse.json({ ok: true })
}

// PATCH /api/focus/:pinId — move a pin between the shared board and your own.
// Body: { shared: boolean }.
//
// Sharing a pin shares the record behind it, in the same gesture: the board is
// useless if pinning something the family can't open, and the alternative is
// making people flip visibility on the underlying list first and then pin it.
// That is only allowed when the caller owns that record — otherwise we would be
// letting one member publish another's private item by pinning it.
export async function PATCH(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 body = await req.json().catch(() => ({}))
  if (typeof body.shared !== 'boolean') return NextResponse.json({ error: 'shared (boolean) required' }, { status: 400 })

  // Only the person who pinned it decides which board it sits on.
  const pin = await db.focusPin.findFirst({
    where: { id, ...owned(session.userId) },
    select: { id: true, reminderId: true, checklistId: true, checklistItem: { select: { listId: true } } },
  })
  if (!pin) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const reminderId = pin.reminderId
  const checklistId = pin.checklistId ?? pin.checklistItem?.listId ?? null

  if (body.shared) {
    // Bring the underlying record along — reminders directly, list items via
    // the list that holds them.
    const promoted = reminderId
      ? await db.reminder.updateMany({ where: { id: reminderId, ...owned(session.userId) }, data: { visibility: 'HOUSEHOLD' } })
      : checklistId
        ? await db.checklist.updateMany({ where: { id: checklistId, ...owned(session.userId) }, data: { visibility: 'HOUSEHOLD' } })
        : { count: 0 }
    if (promoted.count === 0) {
      return NextResponse.json({ error: "you can only share items you own" }, { status: 403 })
    }
  }

  // Taking a reminder off the shared board makes it private again: this button
  // is a reminder's ONLY route to HOUSEHOLD, so unsharing is its exact inverse
  // and leaving it visible would be a one-way door.
  //
  // Lists are deliberately NOT demoted. A list has its own visibility control
  // and defaults to HOUSEHOLD, so it is usually shared for reasons that have
  // nothing to do with this pin — pulling the family's grocery list private
  // because someone tidied their Focus board would be the worse surprise.
  if (!body.shared && reminderId) {
    await db.reminder.updateMany({ where: { id: reminderId, ...owned(session.userId) }, data: { visibility: 'PRIVATE' } })
  }

  await db.focusPin.update({ where: { id }, data: { scope: body.shared ? 'SHARED' : 'PERSONAL' } })
  logActivity(session.userId, body.shared ? 'focus.shared' : 'focus.unshared',
    body.shared ? 'Moved an item to the shared Focus board' : 'Moved an item back to a personal Focus')
  return NextResponse.json({ ok: true })
}
