import {cookies} from 'next/headers';
import {findUserById} from '@/features/auth/mock/users.mock';
import {
  SESSION_COOKIE,
  verifySessionToken,
} from '@/features/auth/services/sessionToken';
import type {AuthSession} from '@/features/auth/types/auth';
import type {ApiSuccess} from '@/shared/types/api';

export const dynamic = 'force-dynamic';

/**
 * GET /api/auth/session
 *
 * The client's only source of truth about who it is. It cannot read the
 * httpOnly cookie, so it asks — and the answer comes from verifying a
 * signature, not from believing something the browser stored.
 *
 * Returns 200 with `data: null` for "no session" rather than 401. A signed-out
 * visitor is a normal state for this endpoint, not an error, and modelling it
 * as one means every caller has to special-case a failure that is not one.
 *
 * The user is re-resolved from the directory rather than read straight off the
 * token: a role change or a deactivation must take effect on the next request,
 * not whenever the cookie happens to expire.
 */
export async function GET(): Promise<Response> {
  const store = await cookies();
  const payload = verifySessionToken(store.get(SESSION_COOKIE)?.value);

  const user = payload ? findUserById(payload.sub) : null;

  const body: ApiSuccess<AuthSession | null> = {
    data:
      payload && user
        ? {user, expiresAt: new Date(payload.exp * 1000).toISOString()}
        : null,
    meta: {generatedAt: new Date().toISOString()},
  };

  return Response.json(body, {headers: {'cache-control': 'no-store'}});
}
