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

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;
  token?: string;
  user?: any;
  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 { firstName, lastName, email, phone, password } = req.body;

  // Validation
  if (!firstName || !lastName || !email || !phone || !password) {
    return res.status(400).json({ error: 'Missing required fields' });
  }

  if (password.length < 8) {
    return res.status(400).json({ error: 'Password must be at least 8 characters' });
  }

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return res.status(400).json({ error: 'Invalid email format' });
  }

  try {
    const connection = await pool.getConnection();

    try {
      // Check if user already exists
      const [existingUsers]: any = await connection.query(
        'SELECT id FROM users WHERE email = ?',
        [email]
      );

      if (existingUsers.length > 0) {
        return res.status(409).json({ error: 'Email already exists' });
      }

      // Hash password
      const saltRounds = 10;
      const hashedPassword = await bcryptjs.hash(password, saltRounds);

      // Insert user
      const [result]: any = await connection.query(
        `INSERT INTO users (first_name, last_name, email, phone, password_hash, is_active, role, created_at, updated_at)
         VALUES (?, ?, ?, ?, ?, 1, 'customer', NOW(), NOW())`,
        [firstName, lastName, email, phone, hashedPassword]
      );

      const userId = result.insertId;

      // Generate email verification token
      const jwtSecret = process.env.JWT_SECRET;
      if (!jwtSecret) {
        throw new Error('JWT_SECRET is not configured');
      }

      const verificationToken = jwt.sign(
        {
          id: userId,
          email: email,
          type: 'email_verification',
        },
        jwtSecret,
        { expiresIn: '24h' }
      );

      // Save verification token to database
      try {
        await connection.query(
          'UPDATE users SET verification_token = ?, verification_token_expires = DATE_ADD(NOW(), INTERVAL 24 HOUR) WHERE id = ?',
          [verificationToken, userId]
        );
      } catch (dbError: any) {
        // If columns don't exist, create them
        if (dbError.code === 'ER_BAD_FIELD_ERROR') {
          await connection.query(
            'ALTER TABLE users ADD COLUMN verification_token VARCHAR(500), ADD COLUMN verification_token_expires DATETIME'
          );
          await connection.query(
            'UPDATE users SET verification_token = ?, verification_token_expires = DATE_ADD(NOW(), INTERVAL 24 HOUR) WHERE id = ?',
            [verificationToken, userId]
          );
        } else {
          throw dbError;
        }
      }

      // Build verification URL
      const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://vystrikejto.cz';
      const verificationUrl = `${baseUrl}/verify-email?token=${encodeURIComponent(verificationToken)}`;

      // Send verification email
      try {
        const emailContent = emailVerificationTemplate({
          customerEmail: email,
          firstName,
          lastName,
          verificationUrl,
        });
        await sendEmail(emailContent);
      } catch (emailError) {
      }

      return res.status(201).json({
        success: true,
        message: 'Registration successful. Please check your email to verify your account.',
        user: {
          id: userId,
          firstName,
          lastName,
          email,
          phone,
        },
      });
    } finally {
      connection.release();
    }
  } catch (error) {
    return res.status(500).json({ error: 'Registration failed. Please try again.' });
  }
}
