import type { NextApiRequest, NextApiResponse } from 'next';
import mysql from 'mysql2/promise';
import jwt from 'jsonwebtoken';
import { sendEmail } from '@/lib/mail';
import { registrationEmailTemplate } from '@/lib/emailTemplates';

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'perfume_shop',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

type ResponseData = {
  success?: boolean;
  message?: string;
  error?: string;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { token } = req.body;

  // Validation
  if (!token) {
    return res.status(400).json({ error: 'Token is required' });
  }

  try {
    const jwtSecret = process.env.JWT_SECRET;
    if (!jwtSecret) {
      throw new Error('JWT_SECRET is not configured');
    }

    // Verify JWT token structure
    const decoded: any = jwt.verify(token, jwtSecret);

    if (decoded.type !== 'email_verification') {
      return res.status(400).json({ error: 'Invalid token type' });
    }

    const connection = await pool.getConnection();

    try {
      // Get user and verify token against database
      const [users]: any = await connection.query(
        'SELECT id, first_name, last_name, email, verification_token, verification_token_expires, is_verified FROM users WHERE id = ?',
        [decoded.id]
      );

      if (users.length === 0) {
        return res.status(404).json({ error: 'User not found' });
      }

      const user = users[0];

      // Check if token matches and hasn't expired
      if (!user.verification_token || user.verification_token !== token) {
        return res.status(400).json({ error: 'Invalid verification token' });
      }

      if (user.verification_token_expires && new Date(user.verification_token_expires) < new Date()) {
        return res.status(400).json({ error: 'Verification link has expired' });
      }

      // Check if email is already verified
      if (user.is_verified) {
        return res.status(400).json({ error: 'Email already verified' });
      }

      // Mark email as verified and clear verification token
      try {
        await connection.query(
          'UPDATE users SET is_verified = 1, email_verified_at = NOW(), verification_token = NULL, verification_token_expires = NULL WHERE id = ?',
          [user.id]
        );
      } catch (dbError: any) {
        // If columns don't exist, create them
        if (dbError.code === 'ER_BAD_FIELD_ERROR') {
          try {
            await connection.query(
              'ALTER TABLE users ADD COLUMN is_verified TINYINT(1) DEFAULT 0, ADD COLUMN email_verified_at DATETIME'
            );
          } catch (alterError: any) {
            // Columns might already exist, try with individual adds
            if (alterError.code === 'ER_DUP_FIELDNAME') {
              // Continue, columns already exist
            } else {
              throw alterError;
            }
          }
          await connection.query(
            'UPDATE users SET is_verified = 1, email_verified_at = NOW(), verification_token = NULL, verification_token_expires = NULL WHERE id = ?',
            [user.id]
          );
        } else {
          throw dbError;
        }
      }

      // Send welcome email
      try {
        const emailContent = registrationEmailTemplate(
          user.email,
          user.first_name,
          user.last_name
        );
        await sendEmail(emailContent);
      } catch (emailError) {
      }

      return res.status(200).json({
        success: true,
        message: 'Email verified successfully! You can now log in.',
      });
    } finally {
      connection.release();
    }
  } catch (error: any) {
    if (error.name === 'TokenExpiredError') {
      return res.status(400).json({ error: 'Verification link has expired' });
    }

    if (error.name === 'JsonWebTokenError') {
      return res.status(400).json({ error: 'Invalid verification link' });
    }

    if (error.message && error.message.includes('Verification link')) {
      return res.status(400).json({ error: error.message });
    }

    return res.status(500).json({
      error: 'Error verifying email. Please try again.',
    });
  }
}
