// app/api/auth/me/route.js

import { getSession } from "@/lib/auth/session";
import { withErrorHandling, json } from "@/lib/api/errors";

/**
 * Force dynamic execution (RHL-006):
 * - auth-related response must never be cached/shared accidentally.
 */
export const dynamic = "force-dynamic";

/**
 * GET /api/auth/me
 *
 * Purpose:
 * - Provide the current session identity for frontend consumers.
 *
 * Semantics (frontend-friendly):
 * - 200 with { user: null } when unauthenticated
 * - 200 with { user: { userId, role, branchId, email, mustChangePassword } } when authenticated
 *
 * This avoids using 401 as control-flow for basic "am I logged in?" checks.
 */
export const GET = withErrorHandling(
	async function GET() {
		const session = await getSession();

		if (!session) {
			return json({ user: null }, 200);
		}

		return json(
			{
				user: {
					userId: session.userId,
					role: session.role,
					branchId: session.branchId ?? null,
					email: session.email ?? null,
					mustChangePassword: session.mustChangePassword === true,
				},
			},
			200,
		);
	},
	{ logPrefix: "[api/auth/me]" },
);
