import { NextRequest, NextResponse } from 'next/server'; import { storeHashDocument, findByPlaintext, findByHash, initializeRedis } from '@/lib/redis'; import { generateHashes, detectHashType } from '@/lib/hash'; export async function POST(request: NextRequest) { try { const { query } = await request.json(); if (!query || typeof query !== 'string') { return NextResponse.json( { error: 'Query parameter is required' }, { status: 400 } ); } // Ensure Redis is connected await initializeRedis(); const cleanQuery = query.trim().split(/\s+/)[0]; if (!cleanQuery) { return NextResponse.json( { error: 'Invalid query: only whitespace provided' }, { status: 400 } ); } const cleanQueryLower = cleanQuery.toLowerCase(); const hashType = detectHashType(cleanQueryLower); if (hashType) { // Query is a hash - search for it in Redis const doc = await findByHash(hashType, cleanQueryLower); if (doc) { // Found matching plaintext return NextResponse.json({ found: true, hashType, hash: cleanQuery, results: [{ plaintext: doc.plaintext, hashes: { md5: doc.md5, sha1: doc.sha1, sha256: doc.sha256, sha512: doc.sha512, } }] }); } else { // Hash not found in database return NextResponse.json({ found: false, hashType, hash: cleanQuery, message: 'Hash not found in database' }); } } else { // Query is plaintext - check if it already exists first const existingDoc = await findByPlaintext(cleanQuery); let hashes; let wasGenerated = false; if (existingDoc) { // Plaintext found, retrieve existing hashes hashes = { md5: existingDoc.md5, sha1: existingDoc.sha1, sha256: existingDoc.sha256, sha512: existingDoc.sha512, }; } else { // Plaintext not found, generate and store hashes hashes = await generateHashes(cleanQuery); await storeHashDocument({ ...hashes, created_at: new Date().toISOString() }); wasGenerated = true; } return NextResponse.json({ found: true, isPlaintext: true, plaintext: cleanQuery, wasGenerated, hashes: { md5: hashes.md5, sha1: hashes.sha1, sha256: hashes.sha256, sha512: hashes.sha512, } }); } } catch (error) { console.error('Search error:', error); return NextResponse.json( { error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } }