import { nanoid } from 'nanoid';
import { sendConfirmationEmail } from './email-confirmation';
import { storage } from './storage';

export function generateVerificationToken(): string {
  return nanoid(32);
}

export async function createVerificationToken(userId: string): Promise<string> {
  const token = generateVerificationToken();
  const expiresAt = new Date();
  expiresAt.setHours(expiresAt.getHours() + 48); // 48 hours from now

  await storage.updateUser(userId, {
    verificationToken: token,
    verificationExpiresAt: expiresAt,
  });

  return token;
}

export async function sendVerificationEmail(
  userId: string, 
  email: string, 
  firstName: string,
  baseUrl: string
): Promise<boolean> {
  try {
    const token = await createVerificationToken(userId);
    
    const emailResult = await sendConfirmationEmail({
      to: email,
      firstName,
      verificationToken: token,
      baseUrl,
    });

    return emailResult;
  } catch (error) {
    console.error('Error sending verification email:', error);
    return false;
  }
}

export async function verifyEmail(token: string): Promise<{ success: boolean; message: string }> {
  try {
    const user = await storage.getUserByVerificationToken(token);
    
    if (!user) {
      return { success: false, message: 'Invalid verification token' };
    }

    if (!user.verificationExpiresAt || new Date() > user.verificationExpiresAt) {
      return { success: false, message: 'Verification token has expired' };
    }

    await storage.updateUser(user.id, {
      emailVerified: true,
      verificationToken: null,
      verificationExpiresAt: null,
    });

    return { success: true, message: 'Email verified successfully' };
  } catch (error) {
    console.error('Error verifying email:', error);
    return { success: false, message: 'Verification failed' };
  }
}