// server/api/admin/village/trigger-tick.post.ts
import { getAuthenticatedUserId } from '../../../utils/auth';
import { getPreviousDay } from '../../../utils/gameDay';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

/**
 * Admin endpoint to manually trigger the game logic tick.
 * This is useful for testing time-based mechanics without waiting.
 * It returns the full, updated village state.
 */
export default defineEventHandler(async (event) => {
  const userId = getAuthenticatedUserId(event);

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

  const [fieldResult, tileResult, villageResult] = await prisma.$transaction([
    // 1. Update lastExpDay for all FIELD objects for this user's village
    prisma.villageObject.updateMany({
      where: {
        village: { userId: userId },
        type: 'FIELD',
      },
      data: {
        lastExpDay: previousDay,
      },
    }),

    // 2. Update clearingStartedDay for all CLEANING VillageTile objects for this user's village
    prisma.villageTile.updateMany({
      where: {
        village: { userId: userId },
        terrainState: 'CLEARING',
      },
      data: {
        clearingStartedDay: previousDay,
      },
    }),

    // 3. Update the village's lastTickDay
    prisma.village.updateMany({
      where: {
        userId: userId,
      },
      data: {
        lastTickDay: previousDay,
      },
    }),
  ]);

  return { 
    success: true, 
    message: `Triggered tick preparation. Fields updated: ${fieldResult.count}, Clearing tiles updated: ${tileResult.count}. Village lastTickDay updated.` 
  };
});
