import { getAuthenticatedUserId } from '../../../utils/auth';

export default defineEventHandler(async (event) => {
  const userId = getAuthenticatedUserId(event);
  const habitId = parseInt(event.context.params?.id || '', 10);

  if (isNaN(habitId)) {
    throw createError({ statusCode: 400, statusMessage: 'Invalid habit ID.' });
  }

  // --- Authorization & Deletion ---
  // First, verify the habit exists and belongs to the user.
  const habit = await prisma.habit.findUnique({
    where: {
      id: habitId,
    },
  });

  if (!habit || habit.userId !== userId) {
    throw createError({ statusCode: 404, statusMessage: 'Habit not found or permission denied.' });
  }

  // Now, delete the habit
  await prisma.habit.delete({
    where: {
      id: habitId,
    },
  });

  // --- Response ---
  // Send 204 No Content status
  setResponseStatus(event, 204);
  
  // Return null or an empty body
  return null;
});
