// server/api/admin/village/reset.post.ts
import { getAuthenticatedUserId } from '../../../utils/auth';
import { generateVillageForUser } from '../../../services/villageService';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default defineEventHandler(async (event) => {
  const userId = getAuthenticatedUserId(event);

  // Simple admin check
  if (userId !== 1) {
    throw createError({ statusCode: 403, statusMessage: 'Forbidden' });
  }

  const user = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
  const village = await prisma.village.findUnique({ where: { userId } });

  if (village) {
    await prisma.$transaction([
      // Note: Order matters due to foreign key constraints.
      // Delete objects first, then tiles.
      prisma.villageObject.deleteMany({ where: { villageId: village.id } }),
      prisma.villageTile.deleteMany({ where: { villageId: village.id } }),
      prisma.village.delete({ where: { id: village.id } }),
    ]);
  }
  
  // Generate a fresh village
  await generateVillageForUser(user);

  return { success: true, message: 'Village has been reset.' };
});
