import { sql } from '../../../lib/sql.js'; import { getUserFromRequest } from '../../../lib/permission-middleware.js'; import { checkStoresRateLimit } from '../../../lib/rate-limit.js'; import { getZipCoords, getStoresNear } from '../../../lib/pricing/geo-cache.js'; import { clampRadiusMiles, milesToMeters } from '../../../lib/pricing/overpass.js'; function isLocalPricingEnabled() { const flag = process.env.PRICING_LOCAL_ENABLED; return flag === undefined || flag === '' || flag === 'true'; } export default async function handler(req, res) { if (req.method !== 'GET') { return res.status(405).json({ error: 'Method not allowed' }); } if (!isLocalPricingEnabled()) { return res.status(503).json({ error: 'Local store discovery is disabled' }); } try { const user = await getUserFromRequest(req); if (!user) { return res.status(401).json({ error: 'Authentication required' }); } const rateLimit = await checkStoresRateLimit(req, user.userId); if (!rateLimit.allowed) { const retryAfterSec = Math.max(1, Math.ceil((rateLimit.reset - Date.now()) / 1000)); res.setHeader('Retry-After', String(retryAfterSec)); return res.status(429).json({ error: 'Rate limit exceeded' }); } const userRow = await sql` SELECT home_zip FROM users WHERE id = ${user.userId} LIMIT 1 `; if (userRow.rows.length === 0) { return res.status(404).json({ error: 'User not found' }); } const homeZip = userRow.rows[0].home_zip; if (!homeZip) { return res.status(400).json({ error: 'Home ZIP not configured', code: 'NO_HOME_ZIP' }); } const radiusMiles = clampRadiusMiles( req.query.radiusMiles != null ? Number(req.query.radiusMiles) : undefined ); const radiusMeters = milesToMeters(radiusMiles); const coords = await getZipCoords(homeZip); if (!coords) { return res.status(404).json({ error: 'Could not geocode home ZIP' }); } const { stores, cached } = await getStoresNear(coords.lat, coords.lng, radiusMeters); return res.status(200).json({ homeZip, radiusMiles, stores, cached, coordsCached: coords.cached, }); } catch (error) { console.error('[stores/nearby]', error); return res.status(500).json({ error: 'Internal server error' }); } }