﻿import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
import { prisma } from '@/lib/prisma';
import { sendActivationEmail } from '@/lib/emailservice.cjs';

// Rate limiting store (in production, use Redis)
const rateLimit = new Map<string, { count: number; lastAttempt: number }>();

export async function POST(request: NextRequest) {
  try {
    const { email } = await request.json();
    
    if (!email) {
      return NextResponse.json(
        { error: 'Email is required' },
        { status: 400 }
      );
    }
    
    // Rate limiting - prevent spam
    const now = Date.now();
    const userLimit = rateLimit.get(email);
    if (userLimit && (now - userLimit.lastAttempt) < 5 * 60 * 1000) {
      if (userLimit.count >= 3) {
        return NextResponse.json(
          { error: 'Too many requests. Please try again later.' },
          { status: 429 }
        );
      }
    }
    
    // Find user with PENDING_ACTIVATION status
    const user = await prisma.user.findFirst({
      where: {
        email,
        status: 'PENDING_ACTIVATION',
      },
    });
    
    if (!user) {
      // For security, don't reveal if user exists
      return NextResponse.json({
        success: true,
        message: 'If an account with this email exists and needs activation, a new link has been sent.',
      });
    }
    
    // Generate new activation token
    const activationToken = crypto.randomBytes(32).toString('hex');
    const tokenExpiry = new Date();
    tokenExpiry.setHours(tokenExpiry.getHours() + 24); // 24 hours expiry
    
    // Update user with new token
    await prisma.user.update({
      where: { id: user.id },
      data: {
        activationToken,
        tokenExpiry,
      },
    });
    
    // Send new activation email
    const emailResult = await sendActivationEmail(
      user.email,
      user.name || 'User',
      activationToken
    );
    
    // Update rate limit
    rateLimit.set(email, {
      count: (userLimit?.count || 0) + 1,
      lastAttempt: now,
    });
    
    if (emailResult && emailResult.success) {
      return NextResponse.json({
        success: true,
        message: 'A new activation link has been sent to your email.',
      });
    } else {
      console.error('Failed to send activation email:', emailResult?.error || 'Unknown error');
      return NextResponse.json(
        { error: 'Failed to send activation email. Please contact HR.' },
        { status: 500 }
      );
    }
    
  } catch (error) {
    console.error('Resend activation error:', error);
    return NextResponse.json(
      { error: 'Failed to resend activation email' },
      { status: 500 }
    );
  }
}