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

// Validates a password-reset link before the reset form is rendered. The account-verification and
// invitation flows this used to serve no longer exist — the owner is created by /auth/bootstrap and
// every other account was inserted by hand, there being no signup route yet.
//
// Deliberately `verify` and not `resolveAuthToken`: this is not an authentication door. It reads a
// purpose-scoped, short-lived reset token, and an API key must never be spendable as one.
export const verifyTokenHandler: Handler = async function (ctx) {
  const { verificationCode } = ctx.get('body');
  if (!verificationCode) throw errors.BAD_REQUEST('Missing verification code');

  let userInfo: User & { purpose?: string };
  try {
    userInfo = (await verify(verificationCode)) as User & { purpose?: string };
  } catch {
    throw errors.BAD_REQUEST('Token is invalid or expired');
  }

  if (userInfo?.purpose !== 'reset-password') throw errors.BAD_REQUEST('Token is invalid or expired');
  if (!userInfo?.id) throw errors.BAD_REQUEST('Token is invalid or expired');

  const user = await getUserById(userInfo.id);
  if (!user) throw errors.NOT_FOUND('User not found');

  return ctx.json({ ok: true, email: user.email });
};
