import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { listUserSessions } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';

/**
 * GET /api/sessions
 * Returns all active sessions for the logged-in user.
 */
export const GET: RequestHandler = async ({ locals }) => {
	if (!locals.user) {
		error(401, 'Not logged in');
	}

	try {
		const sessions = await listUserSessions(locals.user.id);
		// Don't expose raw session_id to the client — only the record ID for revocation
		const safe = sessions.map((s) => ({
			id: s.id,
			user_agent: s.user_agent,
			ip: s.ip,
			created_at: s.created_at,
			last_seen: s.last_seen,
			// Tell the client whether this is the currently active session
			is_current: s.session_id === locals.user!.authSessionId
		}));
		return json({ sessions: safe });
	} catch (e) {
		log.error('sessions', 'GET failed', { err: String(e) });
		error(500, 'Failed to load sessions');
	}
};
