// server/api/admin/village/complete-clearing.post.ts import { getUserIdFromSession } from '../../../utils/auth'; import { PrismaClient } from '@prisma/client'; import { REWARDS } from '../../../services/villageService'; const prisma = new PrismaClient(); export default defineEventHandler(async (event) => { const userId = await getUserIdFromSession(event); // Simple admin check if (userId !== 1) { throw createError({ statusCode: 403, statusMessage: 'Forbidden' }); } const village = await prisma.village.findUniqueOrThrow({ where: { userId } }); const tilesToComplete = await prisma.villageTile.findMany({ where: { villageId: village.id, terrainState: 'CLEARING', }, }); if (tilesToComplete.length === 0) { return { success: true, message: 'No clearing tasks to complete.' }; } const totalCoins = tilesToComplete.length * REWARDS.CLEARING.coins; const totalExp = tilesToComplete.length * REWARDS.CLEARING.exp; await prisma.$transaction(async (tx) => { // 1. Update user totals await tx.user.update({ where: { id: userId }, data: { coins: { increment: totalCoins }, exp: { increment: totalExp }, }, }); // 2. Update all the tiles await tx.villageTile.updateMany({ where: { id: { in: tilesToComplete.map(t => t.id) } }, data: { terrainState: 'IDLE', terrainType: 'EMPTY', clearingStartedAt: null }, }); // 3. Create an event for each completed tile for (const tile of tilesToComplete) { await tx.villageEvent.create({ data: { villageId: village.id, type: tile.terrainType === 'BLOCKED_TREE' ? 'CLEAR_TREE' : 'CLEAR_STONE', message: `Finished clearing ${tile.terrainType === 'BLOCKED_TREE' ? 'a tree' : 'a stone'} at (${tile.x}, ${tile.y})`, tileX: tile.x, tileY: tile.y, coins: REWARDS.CLEARING.coins, exp: REWARDS.CLEARING.exp, } }); } }); return { success: true, message: `Completed ${tilesToComplete.length} clearing tasks.` }; });