'use server'

import { requireSession } from '@/lib/auth'
import {
  createLocation,
  renameLocation,
  moveLocation,
  deleteLocation,
} from '@/lib/locations'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'

export async function addLocation(_prev: unknown, formData: FormData) {
  await requireSession()
  const name = (formData.get('name') as string)?.trim()
  const parentId = (formData.get('parentId') as string) || null
  const notes = (formData.get('notes') as string)?.trim() || null

  if (!name) return { error: 'Name is required' }
  try {
    await createLocation({ name, parentId, notes })
  } catch (e) {
    return { error: e instanceof Error ? e.message : 'Could not create location' }
  }
  revalidatePath('/locations')
  revalidatePath('/items/new')
  return { ok: true }
}

export async function renameLocationAction(id: string, name: string) {
  await requireSession()
  await renameLocation(id, name)
  revalidatePath('/locations')
  revalidatePath(`/locations/${id}`)
}

export async function moveLocationAction(id: string, newParentId: string | null) {
  await requireSession()
  await moveLocation(id, newParentId)
  revalidatePath('/locations')
}

export async function deleteLocationAction(id: string) {
  await requireSession()
  try {
    await deleteLocation(id)
  } catch (e) {
    return { error: e instanceof Error ? e.message : 'Could not delete' }
  }
  revalidatePath('/locations')
  redirect('/locations')
}
