import { NextResponse } from 'next/server';
import dbConnect from '@/lib/db';
import User from '@/models/User';
import { comparePassword, hashPassword } from '@/lib/auth';

export async function POST(req: Request) {
  await dbConnect();
  try {
    const { step, email, answers, newPassword } = await req.json();

    const user = await (User as any).findOne({ email });
    if (!user) {
      // Security: Don't reveal user doesn't exist, but for this app flow we might need to.
      // Let's just return error for now.
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    // Step 1: Return Questions
    if (step === 'get_questions') {
      if (!user.securityQuestion1 || !user.securityQuestion2) {
         return NextResponse.json({ error: 'Security questions not set for this account. Contact support.' }, { status: 400 });
      }
      return NextResponse.json({ 
        questions: [user.securityQuestion1, user.securityQuestion2] 
      });
    }

    // Step 2: Verify Answers and Reset
    if (step === 'verify_reset') {
       const ans1Valid = await comparePassword(answers[0].toLowerCase().trim(), user.securityAnswer1);
       const ans2Valid = await comparePassword(answers[1].toLowerCase().trim(), user.securityAnswer2);

       if (!ans1Valid || !ans2Valid) {
         return NextResponse.json({ error: 'Incorrect answers.' }, { status: 400 });
       }

       // Reset Password
       user.password = await hashPassword(newPassword);
       await user.save();

       return NextResponse.json({ success: true });
    }

    return NextResponse.json({ error: 'Invalid step' }, { status: 400 });

  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Server error' }, { status: 500 });
  }
}
