/** * Debug endpoint for registry sequence counters. * * GET — Show all sequence counters + actual max from entries * POST — Reset all counters to match actual entries (fixes stale counters) * * Auth: NextAuth session only. */ import { NextResponse } from "next/server"; import { prisma } from "@/core/storage/prisma"; import { getAuthSession } from "@/core/auth"; export async function GET() { const session = await getAuthSession(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Get all sequence counters const counters = await prisma.$queryRaw< Array<{ company: string; year: number; type: string; lastSeq: number }> >`SELECT company, year, type, "lastSeq" FROM "RegistrySequence" ORDER BY company, year, type`; // Get actual max sequences from entries // Use Prisma.$queryRawUnsafe to avoid tagged-template escaping issues with regex const actuals = await prisma.$queryRawUnsafe< Array<{ prefix: string; maxSeq: number; count: number }> >(` SELECT SUBSTRING(value::text FROM '"number":"([A-Z]{3}-\\d{4}-(?:IN|OUT|INT))-') AS prefix, MAX(CAST(SUBSTRING(value::text FROM '"number":"[A-Z]{3}-\\d{4}-(?:IN|OUT|INT)-(\\d{5})"') AS INTEGER)) AS "maxSeq", COUNT(*)::int AS count FROM "KeyValueStore" WHERE namespace = 'registratura' AND key LIKE 'entry:%' AND value::text ~ '"number":"[A-Z]{3}-\\d{4}-(IN|OUT|INT)-\\d{5}"' GROUP BY prefix ORDER BY prefix `); return NextResponse.json({ counters, actualEntries: actuals, note: "POST to this endpoint to reset all counters to match actual entries", }); } export async function POST() { const session = await getAuthSession(); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Delete all counters const deleted = await prisma.$executeRaw`DELETE FROM "RegistrySequence"`; // Re-create counters from actual entries const inserted = await prisma.$executeRawUnsafe(` INSERT INTO "RegistrySequence" (id, company, year, type, "lastSeq", "createdAt", "updatedAt") SELECT gen_random_uuid()::text, SUBSTRING(value::text FROM '"number":"([A-Z]+)-') AS company, CAST(SUBSTRING(value::text FROM '"number":"[A-Z]+-(\\d{4})-') AS INTEGER) AS year, SUBSTRING(value::text FROM '"number":"[A-Z]+-\\d{4}-([A-Z]+)-') AS type, MAX(CAST(SUBSTRING(value::text FROM '"number":"[A-Z]+-\\d{4}-[A-Z]+-(\\d{5})"') AS INTEGER)) AS "lastSeq", NOW(), NOW() FROM "KeyValueStore" WHERE namespace = 'registratura' AND key LIKE 'entry:%' AND value::text ~ '"number":"[A-Z]{3}-\\d{4}-(IN|OUT|INT)-\\d{5}"' GROUP BY company, year, type `); return NextResponse.json({ success: true, deletedCounters: deleted, recreatedCounters: inserted, message: "All sequence counters reset to match actual entries", }); }