import { NextResponse } from 'next/server';

import { auth } from '@/lib/auth';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';

/**
 * Self-service password reset for the signed-in CRM user. Calls
 * better-auth's forgetPassword API server-side, which generates a
 * one-time reset token and dispatches the email via the
 * `sendResetPassword` callback configured in src/lib/auth/index.ts.
 *
 * The email always goes to the user's CURRENT account email - no way
 * to redirect to a different inbox here, so the endpoint is safe even
 * if a session is hijacked (the attacker can't move the reset email
 * to themselves).
 */
export const POST = withAuth(async (_req, ctx) => {
  try {
    await auth.api.requestPasswordReset({
      body: {
        email: ctx.user.email,
        // /set-password is the form that actually consumes the token.
        // /reset-password is the "request a link" entry point.
        redirectTo: '/set-password',
      },
    });
    return new NextResponse(null, { status: 204 });
  } catch (error) {
    return errorResponse(error);
  }
});
