habits.andr33v.ru/server/api/admin/village/complete-clearing.post.ts

66 lines
2.1 KiB
TypeScript

// server/api/admin/village/complete-clearing.post.ts
import { getUserIdFromSession } from '../../../utils/auth';
import { PrismaClient } from '@prisma/client';
import { REWARDS } from '../../../utils/economy';
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.VILLAGE.CLEARING.coins;
const totalExp = tilesToComplete.length * REWARDS.VILLAGE.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.VILLAGE.CLEARING.coins,
exp: REWARDS.VILLAGE.CLEARING.exp,
}
});
}
});
return { success: true, message: `Completed ${tilesToComplete.length} clearing tasks.` };
});