// server/api/village/index.get.ts
import { syncAndGetVillage, generateVillageForUser } from '../../services/villageService';
import { defineEventHandler } from 'h3';

export default defineEventHandler(async (event) => {
  const user = event.context.user;

  if (!user) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized',
    });
  }

  // Ensure the user has a village generated. This function is idempotent.
  await generateVillageForUser(user);

  try {
    const villageState = await syncAndGetVillage(user.id);
    return villageState;
  } catch (error: any) {
    // Catch errors from the service and re-throw them as H3 errors
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || 'An error occurred while fetching village state.',
    });
  }
});