import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@utils/prisma"; // Generates code using only the country, and highest id in DB for numbering async function generateEarthquakeCode(type: string, country: string) { const typeLetter = type.trim().charAt(0).toUpperCase(); // Remove non-alphanumeric for the country part const countrySlug = (country || "Unknown").replace(/[^\w]/gi, ""); // Use highest DB id to find the latest added earthquake's code number const last = await prisma.earthquake.findFirst({ orderBy: { id: "desc" }, select: { code: true }, }); let num = 10000; if (last?.code) { const parts = last.code.split("-"); const lastNum = parseInt(parts[parts.length - 1], 10); if (!isNaN(lastNum)) num = lastNum + 1; } return `E${typeLetter}-${countrySlug}-${num.toString().padStart(5, "0")}`; } export async function POST(request: NextRequest) { try { const body = await request.json(); const { date, magnitude, type, location, latitude, longitude, depth, country } = body; const creatorId = 1; if (!date || !magnitude || !type || !location || !latitude || !longitude || !depth || !country) { return NextResponse.json({ error: "Missing fields" }, { status: 400 }); } if (+magnitude > 10) { return NextResponse.json({ error: "Magnitude cannot exceed 10" }, { status: 400 }); } const code = await generateEarthquakeCode(type, country); const eq = await prisma.earthquake.create({ data: { date: new Date(date), code, magnitude: +magnitude, type, location, // "city, country" latitude: +latitude, longitude: +longitude, depth, creatorId, }, }); return NextResponse.json({ id: eq.id, code }, { status: 201 }); } catch (e: any) { return NextResponse.json({ error: e.message }, { status: 500 }); } }