import type { Handler } from 'hono';
import { getUserByEmail } from 'officerdb';
import { sign } from '@@/jwt';
import { sendMail } from 'emailer';

export const forgotPasswordHandler: Handler = async function (ctx) {
  const { email } = ctx.get('body');
  const origin = ctx.get('origin');

  const dbUser = await getUserByEmail(email);

  if (!dbUser) return ctx.json({ ok: true });
  const verificationCode = await sign({ id: dbUser.id, email, purpose: 'reset-password' }, '6h');
  const url = `${origin}/auth/reset-password?verificationCode=${verificationCode}`;

  await sendMail({
    template: 'ForgotPassword',
    subject: 'Reset your officer.dev password',
    to: dbUser.email,
    data: { email: dbUser.email, url },
  });

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