const db = require("../db"); const { reportError } = require("../lib/report-error"); // GPS repository methods (PostgreSQL mode; no DEV_MOCK branch). async function saveGpsTrack(req) { try { const { routeId, latitude, longitude, speed, heading, accuracy } = req.body; if (!routeId || !latitude || !longitude) { return { statusCode: 400, body: { error: "missing_required_fields" } }; } await db.query( ` INSERT INTO gps_tracking (route_id, latitude, longitude, speed_kmh, heading, accuracy, recorded_at) VALUES ($1, $2, $3, $4, $5, $6, NOW()) `, [ routeId, latitude, longitude, speed || null, heading || null, accuracy || null, ], ); return { statusCode: 200, body: { ok: true } }; } catch (err) { console.error(err); reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message }); return { statusCode: 500, body: { error: "internal_error", details: err.message } }; } } async function listRouteGpsPoints(req) { try { const { routeId } = req.params; const userId = req.user.userId; // Verify user owns this route const routeCheck = await db.query( "SELECT id FROM routes WHERE id = $1 AND user_id = $2", [routeId, userId], ); if (routeCheck.rows.length === 0) { return { statusCode: 403, body: { error: "unauthorized" } }; } const result = await db.query( ` SELECT id, latitude, longitude, speed_kmh, heading, accuracy, recorded_at FROM gps_tracking WHERE route_id = $1 ORDER BY recorded_at ASC `, [routeId], ); const positions = result.rows.map((row) => ({ id: row.id, latitude: parseFloat(row.latitude), longitude: parseFloat(row.longitude), speed: row.speed_kmh, heading: row.heading, accuracy: row.accuracy, recordedAt: row.recorded_at, })); return { statusCode: 200, body: { positions } }; } catch (err) { console.error(err); reportError({ partofservice: `${req.method} ${req.originalUrl}`, error: err.stack || err.message }); return { statusCode: 500, body: { error: "internal_error", details: err.message } }; } } module.exports = { saveGpsTrack, listRouteGpsPoints };