import type { User } from 'types';
import type { Handler } from 'hono';
import { updateUser } from 'officerdb';
import { verify } from '@@/jwt';
import argon2 from 'argon2';
import * as errors from '@@/custom-errors';
import { validatePassword } from './validate-password';

export const resetPasswordHandler: Handler = async function (ctx) {
  const { password, verificationCode } = ctx.get('body');
  validatePassword(password);
  const userInfo = (await verify(verificationCode)) as User;
  if (!userInfo) throw errors.UNAUTHORIZED();
  const passwordHash = await argon2.hash(password);
  await updateUser(userInfo.id, { password: passwordHash, status: 'Active', passwordChangedAt: new Date() });

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