import { createResponse } from '@/src/lib/api';
import { db } from '@/lib/db';
import { hash, randomBytes } from 'crypto';
import { EmailService } from '@/src/services/EmailService';

export async function POST(request: Request) {
  const { email } = await request.json();

  const user = await db.user.findUnique({
    where: {
      email,
    },
  });

  if (!user) {
    return createResponse(200, 'User not found');
  }

  const resetToken = randomBytes(64).toString('hex');

  await db.resetToken.create({
    data: {
      userId: user.id,
      token: hash('sha256', resetToken),
      expiresAt: new Date(Date.now() + 15 * 60 * 1000),
    },
  });

  await EmailService.sendPasswordReset(email, user.username ?? 'User', resetToken);

  return createResponse(200, 'Password reset link sent');
}
