import { NextResponse } from 'next/server';
import { prisma } from '../../../../lib/prisma';
import { randomToken, addHours } from '../../../../lib/tokens';
import { sendPasswordResetEmail } from '../../../../lib/mailer';

const APP_URL = process.env.APP_URL || 'http://localhost:3000';

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const email = String(body.email ?? '').trim().toLowerCase();
    if (!email) {
      return NextResponse.json({ error: 'Email is required' }, { status: 400 });
    }

    const user = await prisma.user.findUnique({ where: { email }, select: { id: true, emailVerifiedAt: true } });
    if (user) {
      const token = randomToken();
      await prisma.verificationToken.create({
        data: {
          userId: user.id,
          token,
          type: 'password_reset',
          expiresAt: addHours(2),
        },
      });
      const resetUrl = `${APP_URL}/auth/reset?token=${token}`;
      await sendPasswordResetEmail(email, resetUrl);
    }

    return NextResponse.json({ ok: true });
  } catch (error) {
    console.error('Forgot password error', error);
    return NextResponse.json({ ok: true });
  }
}

export const dynamic = 'force-dynamic';
