import { getAuthenticatedUserId } from '../../utils/auth';
import {
  buildOnTile,
  syncAndGetVillage,
} from '../../services/villageService';

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

  const { tileId, actionType, payload } = body;

  if (!tileId || !actionType) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Missing tileId or actionType',
    });
  }

  switch (actionType) {
    case 'BUILD':
      if (!payload?.buildingType) {
        throw createError({
          statusCode: 400,
          statusMessage: 'Missing buildingType',
        });
      }

      await buildOnTile(userId, tileId, payload.buildingType);
      break;

    default:
      throw createError({
        statusCode: 400,
        statusMessage: 'Invalid actionType',
      });
  }

  return syncAndGetVillage(userId);
});
