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

interface HabitDto {
  id: number;
  name: string;
  daysOfWeek: number[];
}

export default defineEventHandler(async (event): Promise<HabitDto> => {
  const userId = getAuthenticatedUserId(event);
  const habitId = Number(event.context.params?.id);
  const { name, daysOfWeek } = await readBody(event);

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

  // --- Validation ---
  if (!name || !Array.isArray(daysOfWeek)) {
    throw createError({ statusCode: 400, statusMessage: 'Invalid input: name and daysOfWeek are required.' });
  }

  // Sanitize daysOfWeek to ensure it's a unique set of valid numbers
  const validDays = daysOfWeek.filter(day => typeof day === 'number' && day >= 0 && day <= 6);
  const sanitizedDays = [...new Set(validDays)].sort();

  // --- Authorization & Update ---
  // 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, update the habit
  const updatedHabit = await prisma.habit.update({
    where: {
      id: habitId,
    },
    data: {
      name,
      daysOfWeek: sanitizedDays,
    },
  });

  // Return DTO
  return {
    id: updatedHabit.id,
    name: updatedHabit.name,
    daysOfWeek: updatedHabit.daysOfWeek as number[],
  };
});
