import type { Handler } from 'hono';
import type { User } from 'types';
import * as errors from '@@/custom-errors';
import { getUserById, getPasskeysByUserIdAndOrigin } from 'officerdb';

export const usersMe: Handler = async function (ctx) {
  const user = ctx.get('user') as User;
  const origin = ctx.get('origin') as string;

  const dbUser = await getUserById(user.id);

  if (!dbUser) return errors.NOT_FOUND();

  const passkeys = await getPasskeysByUserIdAndOrigin(dbUser.id, origin || '');
  const { password, ...userWithoutPassword } = dbUser;
  const returnUser = { ...userWithoutPassword, passkeyCount: passkeys.length };

  return ctx.json(returnUser);
};
